Building a Blogging Site with React and PHP: A Step-by-Step Guide
WordPress powers over 40% of the web, but even the most experienced users encounter frustrating issues like admin login problems, plugin conflicts, or mysterious white screens. These errors can feel overwhelming, but they don’t have to be.
This guide provides 105 actionable tips and tricks to troubleshoot, debug, and optimize your WordPress site. At any stage of your development career, these solutions will help you tackle common challenges with ease and efficiency. Let’s dive in and get your site running smoothly!
wp_users table (or similar, depending on your table prefix).user_pass field, input a new password and select the MD5 option from the dropdown in the function column.If you prefer direct SQL, use the following query:
UPDATE wp_users
SET user_pass = MD5('newpassword')
WHERE user_login = 'admin';
Replace newpassword with your new password and admin with your admin username.
wp_users table and find your admin user.user_pass field:
functions.php/wp-content/themes/your-active-theme/.functions.php file and add the following code at the end:
function reset_admin_password() {
$user_id = 1; // Replace with the ID of your admin user
wp_set_password('newpassword', $user_id);
}
add_action('init', 'reset_admin_password');
Replace newpassword with your desired password. Save the file and refresh your WordPress site. The system will update the password.
After logging in, immediately remove the added code from functions.php to avoid unnecessary execution.
To manage plugin conflicts, you can disable all plugins directly from the database:
wp_options table.option_name is active_plugins.option_value and clear the content (set it to an empty array: a:0:{}).Edit the wp-config.php file in your WordPress root directory and add:
define('WP_MEMORY_LIMIT', '256M');
If you’re on shared hosting, ask your hosting provider if they support memory increases.
wp-content/plugins folder via FTP or File Manager to deactivate all plugins.wp-content/themes to revert to a default theme like twentytwentythree.WP_DEBUG in wp-config.php:Edit wp-config.php and add or modify the following lines:
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
define('WP_DEBUG_DISPLAY', false);
Errors will now log to the wp-content/debug.log file.
debug.log:Enable WP_DEBUG to record errors, warnings, or notices in the debug.log file. Download and review the file to identify the root cause of issues.
Create must-use plugins for critical features:
wp-content directory and create a folder named mu-plugins if it doesn’t exist.
// Disable XML-RPC for security
add_filter('xmlrpc_enabled', '__return_false');
WordPress automatically loads MU-plugins, and the WordPress admin panel prevents disabling them, ensuring critical features always run.
Restore the site using backups from your hosting provider or a plugin like UpdraftPlus. Always test backups on a staging environment before applying them to the live site.
wp-config.phpFixing URL issues when moving the site to a new domain:
define('WP_HOME', 'https://example.com');
define('WP_SITEURL', 'https://example.com');
Solving permalink or redirect issues by resetting the .htaccess file:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Using simple shell commands to set the correct permissions:
find /path/to/wordpress
-type d -exec chmod
755 {} ;
find /path/to/wordpress
-type f -exec chmod
644 {} ;
Querying for suspicious code in files:
grep -r 'base64_decode'
/path/to/wordpress
Speeding up the site by removing outdated transients:
delete_transient('transient_name');
delete_transient('_transient_timeout_transient_name');
functions.phpPreventing syntax errors by temporarily disabling functions.php changes via FTP or cPanel.
Switching to a default theme using the database:
UPDATE wp_options
SET option_value = 'twentytwentythree'
WHERE option_name = 'template'
OR option_name = 'stylesheet';
Using .htaccess to redirect all traffic to HTTPS:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Protecting the site from brute force attacks:
add_filter('xmlrpc_enabled', '__return_false');
Adding a temporary folder in wp-config.php:
define('WP_TEMP_DIR', dirname(__FILE__) . '/wp-content/temp/');
Re-downloading WordPress core files to fix corrupted installations:
wp core download --force
Cleaning up post revisions, spam comments, and more:
DELETE FROM wp_postmeta
WHERE meta_key = '_wp_old_slug';
Using PHP’s wp_mail() with SMTP:
add_action('phpmailer_init', 'setup_phpmailer');
function setup_phpmailer($phpmailer) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.example.com';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 587;
$phpmailer->Username = 'user@example.com';
$phpmailer->Password = 'password';
}
Adding security to .htaccess:
Options -Indexes
Updating permalinks to regenerate .htaccess via Admin > Settings > Permalinks.
Disabling WordPress cron and setting up a real cron job:
define('DISABLE_WP_CRON', true);
Set up a cron job:
*/15 * * * * wget -q -O -
https://example.com/wp-cron.php?doing_wp_cron
> /dev/null 2>&1
Configuring Memcached or Redis with WordPress.
wp-config.phpMoving wp-config.php to one directory above the WordPress root.
Check and repair the database in wp-config.php:
define('WP_ALLOW_REPAIR', true);
Visit https://example.com/wp-admin/maint/repair.php.
Limit login page access to specific IPs in .htaccess:
<Files wp-login.php>
Order Deny,Allow
Deny from all
Allow from 123.456.789.000
</Files>
Increase upload limits in php.ini:
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
Or in .htaccess:
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
Remove version details from the site header for security:
remove_action('wp_head', 'wp_generator');
Use a cron job to disable plugins unused for months:
if (is_admin() &&
!wp_next_scheduled('deactivate_inactive_plugins')) {
wp_schedule_event(time(),
'daily', 'deactivate_inactive_plugins');
}
add_action('deactivate_inactive_plugins', function() {
$inactive_plugins = get_plugins();
foreach ($inactive_plugins as
$plugin_path => $plugin_info) {
if (!is_plugin_active($plugin_path)) {
deactivate_plugins($plugin_path);
}
}
});
Force HTTPS for all assets using filters:
function fix_mixed_content($content) {
return str_replace('http://',
'https://', $content);
}
add_filter('the_content', 'fix_mixed_content');
Block PHP execution in the uploads directory via .htaccess:
<Files *.php>
deny from all
</Files>
Correct incorrect URL configurations by adding to wp-config.php:
if ($_SERVER['HTTP_X_FORWARDED_PROTO'] ==
'https') $_SERVER['HTTPS'] =
'on';
Recover widgets after theme changes by exporting and importing them using the wp_options table.
Add this snippet to confirm REST API functionality:
add_action('rest_api_init', function() {
echo "REST API is working!";
});
Add a simple honeypot field to forms:
function add_honeypot() {
echo '<input type="hidden" name="honeypot" value="" />';
}
add_action('comment_form', 'add_honeypot');
function check_honeypot($commentdata) {
if (!empty($_POST['honeypot'])) {
wp_die('Spam detected.');
}
return $commentdata;
}
add_filter('preprocess_comment', 'check_honeypot');
Serve files for download using .htaccess:
<FilesMatch ".(pdf|zip|docx)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
</FilesMatch>
Restrict search to posts only (exclude pages):
function search_filter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts', 'search_filter');
Speed up performance by removing emojis:
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
Add to .htaccess for compression:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
Limit the number of revisions for posts in wp-config.php:
define('WP_POST_REVISIONS', 3);
Debug feed issues by flushing permalinks and checking for extra whitespace in functions.php.
Ensure no extra whitespace in files before <?php or after ?>.
View scheduled cron jobs with:
wp_cron();
Enable maintenance mode by creating a maintenance.php file in the root directory.
Temporarily disable scripts for debugging:
add_action('wp_enqueue_scripts', function() {
if (is_admin()) {
wp_dequeue_script('conflicting-script');
}
});
Update all plugins:
wp plugin update --all
Regenerate thumbnails:
wp media regenerate
Reduce server load by limiting the Heartbeat API:
add_action('init', function() {
wp_deregister_script('heartbeat');
});
Increase the memory limit in wp-config.php:
define('WP_MEMORY_LIMIT', '256M');
Create tailored roles for users:
add_role('custom_role', 'Custom Role', [
'read' => true,
'edit_posts' => false,
]);
Insert the Analytics script in the theme header:
add_action('wp_head', function() {
echo "<script>Your Google Analytics Code Here</script>";
});
Prevent updates for specific plugins:
add_filter('site_transient_update_plugins', function($value) {
unset($value->response['plugin-folder/plugin-file.php']);
return $value;
});
Change the admin email directly in wp-config.php:
define('ADMIN_EMAIL', 'your-email@example.com');
Block excessive login attempts using .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .(wp-login|xmlrpc).php*
RewriteCond %{HTTP_REFERER} !^https://example.com.* [OR]
RewriteCond %{REMOTE_ADDR} !^123.123.123.123
RewriteRule .* - [F,L]
</IfModule>
Bypass moderation for trusted users:
add_filter('pre_comment_approved', function($approved, $commentdata) {
if ($commentdata['comment_author_email'] === 'trusted@example.com') {
return 1;
}
return $approved;
}, 10, 2);
Restrict access based on IP using .htaccess:
<Limit GET POST>
Order Deny,Allow
Deny from 192.168.1.0/24
Allow from all
</Limit>
Remove the .maintenance file from the WordPress root to restore the site.
Remove orphaned options to speed up the site:
DELETE FROM wp_options
WHERE autoload = 'yes'
AND option_name LIKE '%_transient_%';
Use wp_login_form() to create a custom login page:
wp_login_form([
'redirect' => site_url('/dashboard/'),
'form_id' => 'custom_login_form',
]);
Schedule a cron job to delete spam comments:
if (!wp_next_scheduled('delete_spam_comments')) {
wp_schedule_event(time(), 'daily', 'delete_spam_comments');
}
add_action('delete_spam_comments', function() {
global $wpdb;
$wpdb->query("DELETE FROM $wpdb->comments WHERE comment_approved = 'spam'");
});
Force missed schedules to run:
add_action('init', function() {
$scheduled_posts = get_posts(['post_status' => 'future']);
foreach ($scheduled_posts as $post) {
wp_publish_post($post->ID);
}
});
Temporarily lock users out after failed attempts:
function block_failed_logins() {
if (!is_user_logged_in() &&
isset($_POST['log'])) {
$ip = $_SERVER['REMOTE_ADDR'];
$failed_attempts = get_transient('failed_login_' . $ip) ?: 0;
if ($failed_attempts >= 5) {
wp_die('Too many failed login attempts. Try again later.');
}
set_transient('failed_login_' . $ip, $failed_attempts + 1, 30 * MINUTE_IN_SECONDS);
}
}
add_action('wp_login_failed', 'block_failed_logins');
Export and import the database using mysqldump:
mysqldump -u username -p database_name > backup.sql
Search and replace URLs using WP-CLI:
wp search-replace
'http://oldsite.com' 'http://newsite.com'
--skip-columns=guid
Restrict REST API access to authenticated users:
add_filter('rest_authentication_errors', function($result) {
if (!is_user_logged_in()) {
return new WP_Error('rest_not_logged_in', 'You are not currently logged in.', [
'status' => 401
]);
}
return $result;
});
Replace the default WordPress admin footer text:
add_filter('admin_footer_text', function() {
echo 'Powered by Your Company';
});
Add lazy loading to images dynamically:
add_filter('the_content', function($content) {
return str_replace('<img', '<img loading="lazy"', $content);
});
Send users to a custom dashboard after login:
add_filter('login_redirect', function($redirect_to, $request, $user) {
if (in_array('subscriber', $user->roles)) {
return site_url('/dashboard/');
}
return $redirect_to;
}, 10, 3);
Add a bot-blocking script to .htaccess:
SetEnvIfNoCase User-Agent "BadBot" bad_bot
Order Allow,Deny
Allow from all
Deny from env=bad_bot
Limit excerpt length and add a “Read More” link:
add_filter('excerpt_more', function() {
return '... <a href="' . get_permalink() .
'">Read More</a>';
});
Adjust REST API permissions:
add_filter('rest_allow_anonymous_comments', '__return_true');
Stop updates for a specific plugin:
add_filter('auto_update_plugin', function($update, $item) {
if ($item->slug === 'plugin-slug') {
return false;
}
return $update;
}, 10, 2);
Enable SVG files in the media library:
add_filter('upload_mimes', function($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
});
Re-enable the Customizer if disabled:
add_action('after_setup_theme', function() {
add_theme_support('customize-selective-refresh-widgets');
});
Add a timeout for inactive users:
add_action('init', function() {
if (is_user_logged_in() && !isset($_COOKIE['user_active'])) {
wp_logout();
}
});
Add rules in .htaccess:
<Files *.php>
deny from all
</Files>
Show a custom maintenance page:
add_action('template_redirect', function() {
if (!is_user_logged_in() && !is_admin()) {
wp_die('Site is under maintenance.');
}
});
Use a custom WP_Query for better search results:
add_action('pre_get_posts', function($query) {
if ($query->is_search && !is_admin()) {
$query->set('post_type', ['post', 'page']);
}
});
Force CSS regeneration:
wp_enqueue_style('theme-styles', get_stylesheet_uri(), [], time());
Define custom redirect URLs:
add_filter('login_redirect', function($redirect_to) {
return home_url('/dashboard/');
});
Check conflicting plugin behavior with:
define('SAVEQUERIES', true);
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
Restrict access using .htaccess:
<Files wp-config.php>
order allow,deny
deny from all
</Files>
Programmatically clear WordPress cache:
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
}
Adjust home and site URL in wp-config.php:
define('WP_HOME', 'https://example.com');
define('WP_SITEURL', 'https://example.com');
Change the WordPress logo on the login page:
add_action('login_enqueue_scripts', function() {
echo '<style>.login h1 a { background-image: url("your-logo.png") !important; }</style>';
});
Use wp_safe_redirect for SEO-safe redirection:
add_action('template_redirect', function() {
if (is_page('old-page')) {
wp_safe_redirect(home_url('/new-page/'));
exit;
}
});
Restrict search results to the past year:
add_action('pre_get_posts', function($query) {
if ($query->is_search) {
$query->set('date_query', [
'after' => '1 year ago',
]);
}
});
Flush rewrite rules programmatically:
add_action('init', function() {
flush_rewrite_rules();
});
Use the no_found_rows parameter in custom queries:
$query = new WP_Query([
'post_type' => 'post',
'no_found_rows' => true,
]);
Add a custom widget to the dashboard:
add_action('wp_dashboard_setup', function() {
wp_add_dashboard_widget('custom_widget', 'Custom Widget', function() {
echo 'Hello, Admin!';
});
});
Increase execution time in .htaccess:
php_value max_execution_time 300
Hide content from unauthorized users:
if (!current_user_can('editor')) {
wp_die('Access denied.');
}
Flush and update permalinks programmatically:
add_action('init', function() {
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
$wp_rewrite->flush_rules();
});
Track admin logins for security:
add_action('wp_login', function($username) {
error_log("Admin {$username} logged in at " . date('Y-m-d H:i:s'));
});
Limit maximum image dimensions:
add_filter('wp_handle_upload_prefilter', function($file) {
$image = getimagesize($file['tmp_name']);
if ($image[0] > 2000 || $image[1] > 2000) {
$file['error'] = 'Images must be less than 2000x2000 pixels.';
}
return $file;
});
Verify user roles on login:
add_action('wp_login', function($username) {
$user = get_user_by('login', $username);
if (in_array('administrator', $user->roles) &&
$user->user_email !== 'admin@example.com') {
wp_die('Unauthorized admin login attempt.');
}
});
Set a custom timezone in wp-config.php:
define('WP_DEFAULT_TIMEZONE', 'America/New_York');
Restrict uploads of potentially harmful file types:
add_filter('upload_mimes', function($mimes) {
unset($mimes['exe']); // Block .exe files
unset($mimes['php']); // Block .php files
return $mimes;
});
Redirect users to a custom 404 error page:
add_action('template_redirect', function() {
if (is_404()) {
wp_redirect(home_url('/custom-error-page/'));
exit;
}
});
Programmatically update all site URLs to HTTPS:
add_action('admin_init', function() {
if (!is_ssl()) {
update_option('siteurl',
str_replace('http://', 'https://',
get_option('siteurl'))
);
update_option('home',
str_replace('http://', 'https://',
get_option('home'))
);
}
});
Add a simple two-factor authentication method:
add_action('login_form', function() {
echo '<p><label for="auth_code">Authentication Code</label>';
echo '<input type="text" name="auth_code" /></p>';
});
add_filter('authenticate', function($user, $username, $password) {
$auth_code = $_POST['auth_code'] ?? '';
if ($username === 'admin' && $auth_code !== '123456') {
return new WP_Error('auth_failed', 'Invalid authentication code.');
}
return $user;
}, 30, 3);
Add Content Security Policy (CSP) headers to prevent malicious scripts:
add_action('send_headers', function() {
header('Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline';');
});
Prevent logged-out users from accessing search functionality:
add_action('template_redirect', function() {
if (!is_user_logged_in() && is_search()) {
wp_redirect(home_url());
exit;
}
});
Lock the admin email to prevent accidental changes:
add_filter('pre_update_option_admin_email', function($value, $old_value) {
return $old_value; // Prevent changes
}, 10, 2);
Save time by auto-approving comments made by admins:
add_filter('pre_comment_approved', function($approved, $commentdata) {
if (user_can($commentdata['user_id'], 'administrator')) {
return 1; // Automatically approve
}
return $approved;
}, 10, 2);
Turn off RSS feeds if they’re not needed:
add_action('do_feed', function() {
wp_redirect(home_url());
exit;
}, 1);
Force inactive users to log out for security:
add_action('init', function() {
if (is_user_logged_in() && isset($_COOKIE['last_activity']) &&
(time() - $_COOKIE['last_activity'] > 1800)) {
wp_logout();
wp_redirect(home_url());
exit;
}
setcookie('last_activity', time(), time() + 1800, COOKIEPATH, COOKIE_DOMAIN);
});
Fixing WordPress issues doesn’t have to be a headache. With these 105 code tricks and practical solutions, you now have a robust toolkit to tackle everything from password resets and debugging to security enhancements and performance optimization.
Let us know in the comments which tip saved your day—or share your own!
💻 Level up with the latest tech trends, tutorials, and tips - Straight to your inbox – no fluff, just value!
Note: Some links on this page might be affiliate links. If you make a purchase through these links, I may earn a small commission at no extra cost to you. Thanks for your support!
Leave a Reply
Your email address will not be published. Required fields are marked *