DEV Community

Cover image for Fix 105 Common WordPress Issues Using Simple Code Snippets
Mainul Hasan
Mainul Hasan

Posted on • Originally published at webdevstory.com

Fix 105 Common WordPress Issues Using Simple Code Snippets

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!

1. Resetting Admin Password via Database

Option 1: Using phpMyAdmin to Update User Passwords

  1. Log in to your hosting control panel and access phpMyAdmin.

  2. Navigate to your WordPress database, then locate and click the wp_users table (or similar, depending on your table prefix).

  3. Find the row corresponding to your admin username.

  4. In the user_pass field, input a new password and select the MD5 option from the dropdown in the function column.

  5. Save your changes. This will reset the password for the specified admin user.

SQL Query for Updating Passwords Securely:

If you prefer direct SQL, use the following query:

UPDATE wp_users
SET user_pass = MD5('newpassword')
WHERE user_login = 'admin';
Enter fullscreen mode Exit fullscreen mode

Replace newpassword with your new password and admin with your admin username.

Option 2: Using Adminer to Update the Password

  1. Upload Adminer to your hosting (download it from Adminer’s website).

  2. Navigate to the Adminer interface through your browser.

  3. Log in with your database credentials.

  4. Locate the wp_users table and find your admin user.

  5. Manually update the user_pass field:

  • Enter the hashed version of your new password (use a hashing tool like a bcrypt generator).

  • If MD5 isn’t working on your server, try other supported hash algorithms like bcrypt or SHA256.

6. Save your changes.

Option 3: Updating Password via functions.php

  1. Access your WordPress site files through FTP or your hosting’s File Manager.

  2. Navigate to the active theme folder under /wp-content/themes/your-active-theme/.

  3. Open the 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');
Enter fullscreen mode Exit fullscreen mode

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.

2. Disabling All Plugins via Database

To manage plugin conflicts, you can disable all plugins directly from the database:

  1. Log in to phpMyAdmin and go to the wp_options table.

  2. Search for the row where option_name is active_plugins.

  3. Edit the option_value and clear the content (set it to an empty array: a:0:{}).

  4. Save your changes to deactivate all plugins. This is useful when a plugin conflict causes issues.

3. Fixing White Screen of Death

Increasing PHP Memory Limits:

Edit the wp-config.php file in your WordPress root directory and add:

define('WP_MEMORY_LIMIT', '256M');
Enter fullscreen mode Exit fullscreen mode

If you’re on shared hosting, ask your hosting provider if they support memory increases.

Checking for Conflicting Plugins or Themes:

  1. Rename the wp-content/plugins folder via FTP or File Manager to deactivate all plugins.

  2. Similarly, rename the active theme folder in wp-content/themes to revert to a default theme like twentytwentythree.

4. Debugging Tips

Enabling 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);
Enter fullscreen mode Exit fullscreen mode

Errors will now log to the wp-content/debug.log file.

Logging Errors to 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.

5. MU-Plugins for Essential Features

Create must-use plugins for critical features:

  1. Navigate to the wp-content directory and create a folder named mu-plugins if it doesn't exist.

  2. Add a PHP file with essential code snippets. For example:

// Disable XML-RPC for security
add_filter('xmlrpc_enabled', '__return_false');
Enter fullscreen mode Exit fullscreen mode

WordPress automatically loads MU-plugins, and the WordPress admin panel prevents disabling them, ensuring critical features always run.

6. Reverting Recent Changes

Using Backups:

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.

Reverting File Changes Through FTP:

  1. Connect to your site via FTP or File Manager.

  2. Replace modified files with their original versions.

  3. If you’re unsure which files you’ve changed, use version control or compare timestamps to identify recent modifications.

7. Changing the Site URL and Home URL via wp-config.php

Fixing URL issues when moving the site to a new domain:

define('WP_HOME', 'https://example.com');
define('WP_SITEURL', 'https://example.com');
Enter fullscreen mode Exit fullscreen mode

8. Restoring the Default .htaccess File

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
Enter fullscreen mode Exit fullscreen mode

9. Fixing File Permissions Issues

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 {} \;
Enter fullscreen mode Exit fullscreen mode

10. Removing Malware or Suspicious Code

Querying for suspicious code in files:

        grep -r 'base64_decode' 
        /path/to/wordpress
Enter fullscreen mode Exit fullscreen mode

11. Clearing Transients from the Database

Speeding up the site by removing outdated transients:

delete_transient('transient_name');
delete_transient('_transient_timeout_transient_name');
Enter fullscreen mode Exit fullscreen mode

12. Fixing Common Errors in functions.php

Preventing syntax errors by temporarily disabling functions.php changes via FTP or cPanel.

13. Restoring the Default Theme

Switching to a default theme using the database:

UPDATE wp_options 
SET option_value = 'twentytwentythree' 
WHERE option_name = 'template' 
OR option_name = 'stylesheet';
Enter fullscreen mode Exit fullscreen mode

14. Forcing HTTPS on the Site

Using .htaccess to redirect all traffic to HTTPS:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
Enter fullscreen mode Exit fullscreen mode

15. Blocking XML-RPC Requests

Protecting the site from brute force attacks:

add_filter('xmlrpc_enabled', '__return_false');
Enter fullscreen mode Exit fullscreen mode

16. Fixing “Upload: Missing a Temporary Folder”

Adding a temporary folder in wp-config.php:

define('WP_TEMP_DIR', dirname(__FILE__) . '/wp-content/temp/');
Enter fullscreen mode Exit fullscreen mode

17. Forcing Reinstall of Core Files

Re-downloading WordPress core files to fix corrupted installations:

 wp core download --force
Enter fullscreen mode Exit fullscreen mode

18. Optimizing the Database

Cleaning up post revisions, spam comments, and more:

DELETE FROM wp_postmeta 
WHERE meta_key = '_wp_old_slug';
Enter fullscreen mode Exit fullscreen mode

19. Fixing Email Sending Issues

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';
}
Enter fullscreen mode Exit fullscreen mode

20. Preventing Directory Browsing

Adding security to .htaccess:

Options -Indexes
Enter fullscreen mode Exit fullscreen mode

21. Regenerating .htaccess with Permalinks

Updating permalinks to regenerate .htaccess via Admin > Settings > Permalinks.

22. Fixing WordPress Cron Jobs

Disabling WordPress cron and setting up a real cron job:

define('DISABLE_WP_CRON', true);
Enter fullscreen mode Exit fullscreen mode

Set up a cron job:

*/15 * * * * wget -q -O - https://example.com/wp-cron.php?doing_wp_cron > /dev/null 2>&1
Enter fullscreen mode Exit fullscreen mode

23. Speed Optimization with Object Caching

Configuring Memcached or Redis with WordPress.

24. Securing wp-config.php

Moving wp-config.php to one directory above the WordPress root.

25. Fixing “Error Establishing Database Connection”

Check and repair the database in wp-config.php:


define('WP_ALLOW_REPAIR', true);
Enter fullscreen mode Exit fullscreen mode

Visit https://example.com/wp-admin/maint/repair.php.

26. Restricting Access to wp-login.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>
Enter fullscreen mode Exit fullscreen mode

27. Fixing Upload Size Limits

Increase upload limits in php.ini:

upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 300
Enter fullscreen mode Exit fullscreen mode

Or in .htaccess:

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
Enter fullscreen mode Exit fullscreen mode

28. Hiding WordPress Version

Remove version details from the site header for security:

remove_action('wp_head', 'wp_generator');
Enter fullscreen mode Exit fullscreen mode

29. Automatically Deactivate Inactive Plugins

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);
   }
  }
 });
Enter fullscreen mode Exit fullscreen mode

30. Fixing Mixed Content Errors

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');
Enter fullscreen mode Exit fullscreen mode

Build a Full Website Using WordPress on Coursera

Master WordPress with Coursera’s guided project and build a full-featured website in just 2 hours. Enroll for free!

31. Preventing PHP Execution in Uploads

Block PHP execution in the uploads directory via .htaccess:

 <Files *.php>
  deny from all
 </Files>
Enter fullscreen mode Exit fullscreen mode

32. Fixing Common Redirect Loops

Correct incorrect URL configurations by adding to wp-config.php:

if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 
'https') $_SERVER['HTTPS'] = 
'on';
Enter fullscreen mode Exit fullscreen mode

33. Restoring Lost Widgets

Recover widgets after theme changes by exporting and importing them using the wp_options table.

34. Debugging REST API Issues

Add this snippet to confirm REST API functionality:

add_action('rest_api_init', function() {
 echo "REST API is working!";
});
Enter fullscreen mode Exit fullscreen mode

35. Preventing Spam Comments

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');
Enter fullscreen mode Exit fullscreen mode

36. Forcing File Download Instead of Opening

Serve files for download using .htaccess:

<FilesMatch "\.(pdf|zip|docx)$">
 ForceType application/octet-stream
 Header set Content-Disposition attachment
</FilesMatch>
Enter fullscreen mode Exit fullscreen mode

37. Fixing Search Query Results

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');
Enter fullscreen mode Exit fullscreen mode

38. Disabling the WP Emoji Script

Speed up performance by removing emojis:

remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
Enter fullscreen mode Exit fullscreen mode

39. Enabling GZIP Compression

Add to .htaccess for compression:

<IfModule mod_deflate.c>
 AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
</IfModule>
Enter fullscreen mode Exit fullscreen mode

40. Preventing Excessive Revisions

Limit the number of revisions for posts in wp-config.php:

define('WP_POST_REVISIONS', 3);
Enter fullscreen mode Exit fullscreen mode

41. Fixing Broken RSS Feeds

Debug feed issues by flushing permalinks and checking for extra whitespace in functions.php.

42. Fixing the “Headers Already Sent” Error

Ensure no extra whitespace in files before <?php or after ?>.

43. Checking Cron Jobs in WordPress

View scheduled cron jobs with:

 wp_cron();
Enter fullscreen mode Exit fullscreen mode

44. Temporarily Hiding Your Website

Enable maintenance mode by creating a maintenance.php file in the root directory.

45. Fixing Page Builder Conflicts

Temporarily disable scripts for debugging:

add_action('wp_enqueue_scripts', function() {
 if (is_admin()) {
  wp_dequeue_script('conflicting-script');
 }
});
Enter fullscreen mode Exit fullscreen mode

46. Using WP-CLI for Bulk Actions

Update all plugins:

wp plugin update --all
Enter fullscreen mode Exit fullscreen mode

Regenerate thumbnails:

wp media regenerate
Enter fullscreen mode Exit fullscreen mode

47. Disabling WordPress Heartbeat API

Reduce server load by limiting the Heartbeat API:

add_action('init', function() {
 wp_deregister_script('heartbeat');
});
Enter fullscreen mode Exit fullscreen mode

48. Fixing Memory Exhaustion Errors

Increase the memory limit in wp-config.php:

define('WP_MEMORY_LIMIT', '256M');
Enter fullscreen mode Exit fullscreen mode

49. Adding Custom User Roles

Create tailored roles for users:

add_role('custom_role', 'Custom Role', [
'read' => true,
'edit_posts' => false,
]);
Enter fullscreen mode Exit fullscreen mode

50. Adding Google Analytics Without Plugins

Insert the Analytics script in the theme header:

add_action('wp_head', function() {
 echo "<script>Your Google Analytics Code Here</script>";
});
Enter fullscreen mode Exit fullscreen mode

51. Disabling Plugin Updates

Prevent updates for specific plugins:

add_filter('site_transient_update_plugins', function($value) {
 unset($value->response['plugin-folder/plugin-file.php']);
 return $value;
});
Enter fullscreen mode Exit fullscreen mode

52. Overwriting Default Admin Email

Change the admin email directly in wp-config.php:

define('ADMIN_EMAIL', 'your-email@example.com');
Enter fullscreen mode Exit fullscreen mode

53. Preventing Brute Force Attacks

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>
Enter fullscreen mode Exit fullscreen mode

54. Automatically Approving Comments from Known Users

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);
Enter fullscreen mode Exit fullscreen mode

55. Blocking Specific Countries

Restrict access based on IP using .htaccess:

<Limit GET POST>
 Order Deny,Allow
 Deny from 192.168.1.0/24
 Allow from all
</Limit>
Enter fullscreen mode Exit fullscreen mode

56. Fixing Stuck Maintenance Mode

Remove the .maintenance file from the WordPress root to restore the site.

57. Cleaning the wp_options Table

Remove orphaned options to speed up the site:

DELETE FROM wp_options 
WHERE autoload = 'yes' 
AND option_name LIKE '%_transient_%';
Enter fullscreen mode Exit fullscreen mode

58. Creating a Custom Login Page

Use wp_login_form() to create a custom login page:

wp_login_form([
'redirect' => site_url('/dashboard/'),
'form_id' => 'custom_login_form',
]);
Enter fullscreen mode Exit fullscreen mode

59. Automatically Deleting Spam Comments

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'");
});
Enter fullscreen mode Exit fullscreen mode

60. Fixing Broken Scheduled Posts

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);
 }
});
Enter fullscreen mode Exit fullscreen mode

61. Limiting WordPress Login Attempts

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');
Enter fullscreen mode Exit fullscreen mode

62. Migrating WordPress Without Plugins

Export and import the database using mysqldump:

mysqldump -u username -p database_name > backup.sql
Enter fullscreen mode Exit fullscreen mode

Search and replace URLs using WP-CLI:

wp search-replace 
'http://oldsite.com' 'http://newsite.com' 
--skip-columns=guid
Enter fullscreen mode Exit fullscreen mode

63. Improving REST API Security

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;
});
Enter fullscreen mode Exit fullscreen mode

64. Customizing the Admin Footer

Replace the default WordPress admin footer text:

add_filter('admin_footer_text', function() {
 echo 'Powered by Your Company';
});
Enter fullscreen mode Exit fullscreen mode

65. Enabling Lazy Loading for Images

Add lazy loading to images dynamically:

add_filter('the_content', function($content) {
 return str_replace('<img', '<img loading="lazy"', $content);
});
Enter fullscreen mode Exit fullscreen mode

66. Redirecting Users After Login

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);
Enter fullscreen mode Exit fullscreen mode

67. Blocking Bad Bots

Add a bot-blocking script to .htaccess:

 SetEnvIfNoCase User-Agent "BadBot" bad_bot
 Order Allow,Deny
 Allow from all
 Deny from env=bad_bot
Enter fullscreen mode Exit fullscreen mode

68. Customizing Excerpts

Limit excerpt length and add a “Read More” link:

add_filter('excerpt_more', function() {
 return '... <a href="' . get_permalink() . 
 '">Read More</a>';
});
Enter fullscreen mode Exit fullscreen mode

69. Fixing JSON Error in Gutenberg Editor

Adjust REST API permissions:

 add_filter('rest_allow_anonymous_comments', '__return_true');
Enter fullscreen mode Exit fullscreen mode

70. Disabling Auto-Updates for Specific Plugins

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);
Enter fullscreen mode Exit fullscreen mode

WordPress Academy: Learn WordPress Step by Step on Skillshare

Discover the basics of WordPress with the WordPress Academy course on Skillshare. Start your free trial today!

71. Allowing SVG Uploads

Enable SVG files in the media library:

add_filter('upload_mimes', function($mimes) {
 $mimes['svg'] = 'image/svg+xml';
 return $mimes;
});
Enter fullscreen mode Exit fullscreen mode

72. Fixing Missing Customizer Options

Re-enable the Customizer if disabled:

add_action('after_setup_theme', function() {
 add_theme_support('customize-selective-refresh-widgets');
});
Enter fullscreen mode Exit fullscreen mode

73. Automatically Log Out Inactive Users

Add a timeout for inactive users:

add_action('init', function() {
 if (is_user_logged_in() && !isset($_COOKIE['user_active'])) {
  wp_logout();
 }
});
Enter fullscreen mode Exit fullscreen mode

74. Preventing Direct Access to PHP Files

Add rules in .htaccess:

Files *.php>
deny from all
</Files>
Enter fullscreen mode Exit fullscreen mode

75. Custom Maintenance Mode

Show a custom maintenance page:

add_action('template_redirect', function() {
 if (!is_user_logged_in() && !is_admin()) {
  wp_die('Site is under maintenance.');
 }
});
Enter fullscreen mode Exit fullscreen mode

76. Optimizing WordPress Search with Custom Queries

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']);
 }
});
Enter fullscreen mode Exit fullscreen mode

77. Fixing Broken Theme Styles

Force CSS regeneration:

 wp_enqueue_style('theme-styles', get_stylesheet_uri(), [], time());
Enter fullscreen mode Exit fullscreen mode

78. Fixing Redirect Issues for Login/Logout

Define custom redirect URLs:

add_filter('login_redirect', function($redirect_to) {
 return home_url('/dashboard/');
});
Enter fullscreen mode Exit fullscreen mode

79. Enabling Debugging for Plugin Conflicts

Check conflicting plugin behavior with:

define('SAVEQUERIES', true);
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
Enter fullscreen mode Exit fullscreen mode

80. Protecting wp-config.php

Restrict access using .htaccess:

<Files wp-config.php>
 order allow,deny
 deny from all
</Files>
Enter fullscreen mode Exit fullscreen mode

81. Clearing Cache Programmatically

Programmatically clear WordPress cache:

if (function_exists('wp_cache_flush')) {
 wp_cache_flush();
}
Enter fullscreen mode Exit fullscreen mode

82. Fixing “Too Many Redirects” Error

Adjust home and site URL in wp-config.php:

define('WP_HOME', 'https://example.com');
define('WP_SITEURL', 'https://example.com');
Enter fullscreen mode Exit fullscreen mode

83. Customizing the Login Page Logo

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>';
});
Enter fullscreen mode Exit fullscreen mode

84. Redirecting Old URLs to New Ones

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;
 }
});
Enter fullscreen mode Exit fullscreen mode

85. Limiting Search Queries by Date

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',
  ]);
 }
});
Enter fullscreen mode Exit fullscreen mode

How to Use Elementor: Build an Awesome WordPress Website With No Code on Skillshare

Learn to create professional WordPress websites using Elementor without writing a single line of code. Available on Skillshare!

86. Fixing 404 Errors for Custom Post Types

Flush rewrite rules programmatically:

add_action('init', function() {
 flush_rewrite_rules();
});
Enter fullscreen mode Exit fullscreen mode

87. Speeding Up WordPress Queries

Use the no_found_rows parameter in custom queries:

$query = new WP_Query([
'post_type' => 'post',
'no_found_rows' => true,
]);
Enter fullscreen mode Exit fullscreen mode

88. Customizing the WordPress Admin Dashboard

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!';
 });
});
Enter fullscreen mode Exit fullscreen mode

89. Fixing Long Execution Times

Increase execution time in .htaccess:

php_value max_execution_time 300
Enter fullscreen mode Exit fullscreen mode

90. Restricting Content by User Role

Hide content from unauthorized users:

if (!current_user_can('editor')) {
 wp_die('Access denied.');
}
Enter fullscreen mode Exit fullscreen mode

91. Automatically Updating Permalinks

Flush and update permalinks programmatically:

add_action('init', function() {
 global $wp_rewrite;
 $wp_rewrite->set_permalink_structure('/%postname%/');
 $wp_rewrite->flush_rules();
});
Enter fullscreen mode Exit fullscreen mode

92. Monitoring Admin Logins

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'));
});
Enter fullscreen mode Exit fullscreen mode

93. Preventing Large Image Uploads

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;
});
Enter fullscreen mode Exit fullscreen mode

94. Detecting and Blocking Fake Admins

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.');
 }
});
Enter fullscreen mode Exit fullscreen mode

95. Fixing Timezone Issues

Set a custom timezone in wp-config.php:

define('WP_DEFAULT_TIMEZONE', 'America/New_York');
Enter fullscreen mode Exit fullscreen mode

96. Preventing the Upload of Certain File Types

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;
});
Enter fullscreen mode Exit fullscreen mode

97. Creating a Custom Error Page

Redirect users to a custom 404 error page:

add_action('template_redirect', function() {
 if (is_404()) {
  wp_redirect(home_url('/custom-error-page/'));
  exit;
 }
});
Enter fullscreen mode Exit fullscreen mode

98. Automatically Updating SSL Settings

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'))
  );
 }
});
Enter fullscreen mode Exit fullscreen mode

99. Adding Two-Factor Authentication for Admins

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);
Enter fullscreen mode Exit fullscreen mode

100. Improving Site Security with CSP Headers

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\';');
});
Enter fullscreen mode Exit fullscreen mode

101. Disable Search for Logged-Out Users

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;
 }
});
Enter fullscreen mode Exit fullscreen mode

102. Prevent Users from Changing Admin Email

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);
Enter fullscreen mode Exit fullscreen mode

103. Automatically Approve Admin Comments

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);
Enter fullscreen mode Exit fullscreen mode

104. Disable RSS Feeds

Turn off RSS feeds if they’re not needed:

add_action('do_feed', function() {
 wp_redirect(home_url());
 exit;
}, 1);
Enter fullscreen mode Exit fullscreen mode

105. Automatically Log Out Users After a Period

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);
});
Enter fullscreen mode Exit fullscreen mode

Wrapping It Up: A Troubleshooter’s Toolbox

Fixing WordPress issues doesn’t have to be a headache. With these 105 code tricks and practical solutions, you 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!

🚀 Before You Go:

👏 Found these JavaScript mastery tips useful? Give it a clap!
💬 Have your own tips? Share them in the comments!
🔄 Know someone learning JavaScript? Share this post with them!

🌟 Your support keeps us going!

📩 Get the latest tutorials, tips, and tech updates right in your inbox!

👉 Subscribe

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!

Top comments (0)