Fix 105 Common WordPress Issues Using Simple Code Snippets

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';        

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');        

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');        

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);        

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');        

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');        

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        

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 {} \;        

10. Removing Malware or Suspicious Code

Querying for suspicious code in files:

        grep -r 'base64_decode' 
        /path/to/wordpress        

11. Clearing Transients from the Database

Speeding up the site by removing outdated transients:

delete_transient('transient_name');
delete_transient('_transient_timeout_transient_name');        

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';        

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]        

15. Blocking XML-RPC Requests

Protecting the site from brute force attacks:

add_filter('xmlrpc_enabled', '__return_false');        

16. Fixing “Upload: Missing a Temporary Folder”

Adding a temporary folder in wp-config.php:

define('WP_TEMP_DIR', dirname(__FILE__) . '/wp-content/temp/');        

17. Forcing Reinstall of Core Files

Re-downloading WordPress core files to fix corrupted installations:

 wp core download --force        

18. Optimizing the Database

Cleaning up post revisions, spam comments, and more:

DELETE FROM wp_postmeta 
WHERE meta_key = '_wp_old_slug';        

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 = '[email protected]';
 $phpmailer->Password = 'password';
}        

20. Preventing Directory Browsing

Adding security to .htaccess:

Options -Indexes        

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);        

Set up a cron job:

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

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);        

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>        

27. Fixing Upload Size Limits

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        

28. Hiding WordPress Version

Remove version details from the site header for security:

remove_action('wp_head', 'wp_generator');        

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);
   }
  }
 });        


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!

30. Fixing Mixed Content Errors

Force HTTPS for all assets using filters:

function fix_mixed_content($content) {
 return str_replace('https://', 
 'https://', $content);
}
add_filter('the_content', 'fix_mixed_content');        

31. Preventing PHP Execution in Uploads

Block PHP execution in the uploads directory via .htaccess:

 <Files *.php>
  deny from all
 </Files>        

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';        

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!";
});        

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');        

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>        

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');        

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');        

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>        

40. Preventing Excessive Revisions

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

define('WP_POST_REVISIONS', 3);        

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();        

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');
 }
});        

46. Using WP-CLI for Bulk Actions

Update all plugins:

wp plugin update --all        

Regenerate thumbnails:

wp media regenerate        

47. Disabling WordPress Heartbeat API

Reduce server load by limiting the Heartbeat API:

add_action('init', function() {
 wp_deregister_script('heartbeat');
});        

48. Fixing Memory Exhaustion Errors

Increase the memory limit in wp-config.php:

define('WP_MEMORY_LIMIT', '256M');        

49. Adding Custom User Roles

Create tailored roles for users:

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

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>";
});        

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;
});        

52. Overwriting Default Admin Email

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

define('ADMIN_EMAIL', '[email protected]');        

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>        

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'] === '[email protected]') {
  return 1;
 }
 return $approved;
}, 10, 2);        

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>        

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_%';        

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',
]);        

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'");
});        


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!

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);
 }
});        

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');        

62. Migrating WordPress Without Plugins

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 
'https://oldsite.com' 'https://newsite.com' 
--skip-columns=guid        

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;
});        

64. Customizing the Admin Footer

Replace the default WordPress admin footer text:

add_filter('admin_footer_text', function() {
 echo 'Powered by Your Company';
});        

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);
});        

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);        

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        

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>';
});        

69. Fixing JSON Error in Gutenberg Editor

Adjust REST API permissions:

 add_filter('rest_allow_anonymous_comments', '__return_true');        

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);        

71. Allowing SVG Uploads

Enable SVG files in the media library:

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

72. Fixing Missing Customizer Options

Re-enable the Customizer if disabled:

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

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();
 }
});        

74. Preventing Direct Access to PHP Files

Add rules in .htaccess:

Files *.php>
deny from all
</Files>        

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.');
 }
});        

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']);
 }
});        

77. Fixing Broken Theme Styles

Force CSS regeneration:

 wp_enqueue_style('theme-styles', get_stylesheet_uri(), [], time());        

78. Fixing Redirect Issues for Login/Logout

Define custom redirect URLs:

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

79. Enabling Debugging for Plugin Conflicts

Check conflicting plugin behavior with:

define('SAVEQUERIES', true);
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);        

80. Protecting wp-config.php

Restrict access using .htaccess:

<Files wp-config.php>
 order allow,deny
 deny from all
</Files>        

81. Clearing Cache Programmatically

Programmatically clear WordPress cache:

if (function_exists('wp_cache_flush')) {
 wp_cache_flush();
}        

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');        

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>';
});        

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;
 }
});        

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',
  ]);
 }
});        

86. Fixing 404 Errors for Custom Post Types

Flush rewrite rules programmatically:

add_action('init', function() {
 flush_rewrite_rules();
});        

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,
]);        

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!';
 });
});        

89. Fixing Long Execution Times

Increase execution time in .htaccess:

php_value max_execution_time 300        

90. Restricting Content by User Role

Hide content from unauthorized users:

if (!current_user_can('editor')) {
 wp_die('Access denied.');
}        

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();
});        

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'));
});        

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;
});        

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 !== '[email protected]') {
  wp_die('Unauthorized admin login attempt.');
 }
});        

95. Fixing Timezone Issues

Set a custom timezone in wp-config.php:

define('WP_DEFAULT_TIMEZONE', 'America/New_York');        


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!

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;
});        

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;
 }
});        

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('https://', 'https://', 
  get_option('siteurl'))
  );
  update_option('home', 
  str_replace('https://', 'https://', 
  get_option('home'))
  );
 }
});        

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);        

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\';');
});        

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;
 }
});        

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);        

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);        

104. Disable RSS Feeds

Turn off RSS feeds if they’re not needed:

add_action('do_feed', function() {
 wp_redirect(home_url());
 exit;
}, 1);        

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);
});        

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 cloud storage tips helpful? Give it a clap!

?? Have your own tips? Share them in the comments!

?? Know someone who needs this? Share the post!

?? Your support keeps us going!


?? Stay updated with the latest tech trends, tutorials, and tips straight to 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!

Originally published at https://www.webdevstory.com on January 15, 2025.

要查看或添加评论,请登录

Mainul Hasan的更多文章