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 Log in to your hosting control panel and access phpMyAdmin. Navigate to your WordPress database, then locate and click the wp_users table (or similar, depending on your table prefix). Find the row corresponding to your admin username. In the user_pass field, input a new password and select the MD5 option from the dropdown in the function column. 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 Upload Adminer to your hosting (download it from Adminer’s website). Navigate to the Adminer interface through your browser. Log in with your database credentials. Locate the wp_users table and find your admin user. 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 Access your WordPress site files through FTP or your hosting’s File Manager. Navigate to the active theme folder under /wp-content/themes/your-active-theme/. 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: Log in to phpMyAdmin and go to the wp_options table. Search for the row where option_name is active_plugins. Edit the option_value and clear the content (set it to an empty array: a:0:{}). 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: Rename the wp-content/plugins folder via FTP or File Manager to deactivate all plugins. 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: Navigate to the wp-content directory and create a folder named mu-plugins if it doesn't exist. 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: Connect to your site via FTP or File Manager. Replace modified files with their original versions. If you’re unsure which files you’ve changed, use version control or compare timestamps to identify recent modifications.
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
Log in to your hosting control panel and access phpMyAdmin.
Navigate to your WordPress database, then locate and click the
wp_users
table (or similar, depending on your table prefix).Find the row corresponding to your admin username.
In the
user_pass
field, input a new password and select the MD5 option from the dropdown in the function column.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
Upload Adminer to your hosting (download it from Adminer’s website).
Navigate to the Adminer interface through your browser.
Log in with your database credentials.
Locate the
wp_users
table and find your admin user.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
Access your WordPress site files through FTP or your hosting’s File Manager.
Navigate to the active theme folder under
/wp-content/themes/your-active-theme/
.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:
Log in to phpMyAdmin and go to the
wp_options
table.Search for the row where
option_name
isactive_plugins
.Edit the
option_value
and clear the content (set it to an empty array:a:0:{}
).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:
Rename the
wp-content/plugins
folder via FTP or File Manager to deactivate all plugins.Similarly, rename the active theme folder in
wp-content/themes
to revert to a default theme liketwentytwentythree
.
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:
Navigate to the
wp-content
directory and create a folder namedmu-plugins
if it doesn't exist.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:
Connect to your site via FTP or File Manager.
Replace modified files with their original versions.
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 = 'user@example.com';
$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
:
wp-login.php>
Order Deny,Allow
Deny from all
Allow from 123.456.789.000
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);
}
}
});
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');
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
:
*.php>
deny from all
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 '';
}
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
:
"\.(pdf|zip|docx)$">
ForceType application/octet-stream
Header set Content-Disposition attachment
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:
mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript application/json
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 View scheduled cron jobs with: Enable maintenance mode by creating a Temporarily disable scripts for debugging: Update all plugins: Regenerate thumbnails: Reduce server load by limiting the Heartbeat API: Increase the memory limit in Create tailored roles for users: Insert the Analytics script in the theme header: Prevent updates for specific plugins: Change the admin email directly in Block excessive login attempts using Bypass moderation for trusted users: Restrict access based on IP using Remove the Remove orphaned options to speed up the site: Use Schedule a cron job to delete spam comments: Force missed schedules to run: Temporarily lock users out after failed attempts: Export and import the database using Search and replace URLs using WP-CLI: Restrict REST API access to authenticated users: Replace the default WordPress admin footer text: Add lazy loading to images dynamically: Send users to a custom dashboard after login: Add a bot-blocking script to Limit excerpt length and add a “Read More” link: Adjust REST API permissions: Stop updates for a specific plugin:
Discover the basics of WordPress with the WordPress Academy course on Skillshare. Start your free trial today!
Enable SVG files in the media library: Re-enable the Customizer if disabled: Add a timeout for inactive users: Add rules in Show a custom maintenance page: Use a custom Force CSS regeneration: Define custom redirect URLs: Check conflicting plugin behavior with: Restrict access using Programmatically clear WordPress cache: Adjust home and site URL in Change the WordPress logo on the login page: Use Restrict search results to the past year:
Learn to create professional WordPress websites using Elementor without writing a single line of code. Available on Skillshare!
Flush rewrite rules programmatically: Use the Add a custom widget to the dashboard: Increase execution time in Hide content from unauthorized users: Flush and update permalinks programmatically: Track admin logins for security: Limit maximum image dimensions: Verify user roles on login: Set a custom timezone in Restrict uploads of potentially harmful file types: Redirect users to a custom 404 error page: Programmatically update all site URLs to HTTPS: Add a simple two-factor authentication method: ' Add Content Security Policy (CSP) headers to prevent malicious scripts: Prevent logged-out users from accessing search functionality: Lock the admin email to prevent accidental changes: Save time by auto-approving comments made by admins: Turn off RSS feeds if they’re not needed: Force inactive users to log out for security: 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!
or after
?>
.
43. Checking Cron Jobs in WordPress
wp_cron();
44. Temporarily Hiding Your Website
maintenance.php
file in the root directory.
45. Fixing Page Builder Conflicts
add_action('wp_enqueue_scripts', function() {
if (is_admin()) {
wp_dequeue_script('conflicting-script');
}
});
46. Using WP-CLI for Bulk Actions
wp plugin update --all
wp media regenerate
47. Disabling WordPress Heartbeat API
add_action('init', function() {
wp_deregister_script('heartbeat');
});
48. Fixing Memory Exhaustion Errors
wp-config.php
:
define('WP_MEMORY_LIMIT', '256M');
49. Adding Custom User Roles
add_role('custom_role', 'Custom Role', [
'read' => true,
'edit_posts' => false,
]);
50. Adding Google Analytics Without Plugins
add_action('wp_head', function() {
echo "";
});
51. Disabling Plugin Updates
add_filter('site_transient_update_plugins', function($value) {
unset($value->response['plugin-folder/plugin-file.php']);
return $value;
});
52. Overwriting Default Admin Email
wp-config.php
:
define('ADMIN_EMAIL', 'your-email@example.com');
53. Preventing Brute Force Attacks
.htaccess
:
54. Automatically Approving Comments from Known Users
add_filter('pre_comment_approved', function($approved, $commentdata) {
if ($commentdata['comment_author_email'] === 'trusted@example.com') {
return 1;
}
return $approved;
}, 10, 2);
55. Blocking Specific Countries
.htaccess
:
56. Fixing Stuck Maintenance Mode
.maintenance
file from the WordPress root to restore the site.
57. Cleaning the wp_options Table
DELETE FROM wp_options
WHERE autoload = 'yes'
AND option_name LIKE '%_transient_%';
58. Creating a Custom Login Page
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
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'");
});
60. Fixing Broken Scheduled Posts
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
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
mysqldump
:
mysqldump -u username -p database_name > backup.sql
wp search-replace
'http://oldsite.com' 'http://newsite.com'
--skip-columns=guid
63. Improving REST API Security
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
add_filter('admin_footer_text', function() {
echo 'Powered by Your Company';
});
65. Enabling Lazy Loading for Images
add_filter('the_content', function($content) {
return str_replace(', ', $content);
});
66. Redirecting Users 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
.htaccess
:
SetEnvIfNoCase User-Agent "BadBot" bad_bot
Order Allow,Deny
Allow from all
Deny from env=bad_bot
68. Customizing Excerpts
add_filter('excerpt_more', function() {
return '... . get_permalink() .
'">Read More';
});
69. Fixing JSON Error in Gutenberg Editor
add_filter('rest_allow_anonymous_comments', '__return_true');
70. Disabling Auto-Updates for Specific Plugins
add_filter('auto_update_plugin', function($update, $item) {
if ($item->slug === 'plugin-slug') {
return false;
}
return $update;
}, 10, 2);
71. Allowing SVG Uploads
add_filter('upload_mimes', function($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
});
72. Fixing Missing Customizer Options
add_action('after_setup_theme', function() {
add_theme_support('customize-selective-refresh-widgets');
});
73. Automatically Log Out Inactive Users
add_action('init', function() {
if (is_user_logged_in() && !isset($_COOKIE['user_active'])) {
wp_logout();
}
});
74. Preventing Direct Access to PHP Files
.htaccess
:
Files *.php>
deny from all
Files>
75. Custom Maintenance Mode
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
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
wp_enqueue_style('theme-styles', get_stylesheet_uri(), [], time());
78. Fixing Redirect Issues for Login/Logout
add_filter('login_redirect', function($redirect_to) {
return home_url('/dashboard/');
});
79. Enabling Debugging for Plugin Conflicts
define('SAVEQUERIES', true);
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
80. Protecting wp-config.php
.htaccess
:
81. Clearing Cache Programmatically
if (function_exists('wp_cache_flush')) {
wp_cache_flush();
}
82. Fixing “Too Many Redirects” Error
wp-config.php
:
define('WP_HOME', 'https://example.com');
define('WP_SITEURL', 'https://example.com');
83. Customizing the Login Page Logo
add_action('login_enqueue_scripts', function() {
echo '';
});
84. Redirecting Old URLs to New Ones
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
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
add_action('init', function() {
flush_rewrite_rules();
});
87. Speeding Up WordPress Queries
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_action('wp_dashboard_setup', function() {
wp_add_dashboard_widget('custom_widget', 'Custom Widget', function() {
echo 'Hello, Admin!';
});
});
89. Fixing Long Execution Times
.htaccess
:
php_value max_execution_time 300
90. Restricting Content by User Role
if (!current_user_can('editor')) {
wp_die('Access denied.');
}
91. Automatically Updating Permalinks
add_action('init', function() {
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
$wp_rewrite->flush_rules();
});
92. Monitoring Admin Logins
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
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
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.');
}
});
95. Fixing Timezone Issues
wp-config.php
:
define('WP_DEFAULT_TIMEZONE', 'America/New_York');
96. Preventing the Upload of Certain 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
add_action('template_redirect', function() {
if (is_404()) {
wp_redirect(home_url('/custom-error-page/'));
exit;
}
});
98. Automatically Updating SSL Settings
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'))
);
}
});
99. Adding Two-Factor Authentication for Admins
add_action('login_form', function() {
echo '
100. Improving Site Security with CSP Headers
add_action('send_headers', function() {
header('Content-Security-Policy: default-src \'self\'; script-src \'self\' \'unsafe-inline\';');
});
101. Disable Search for Logged-Out Users
add_action('template_redirect', function() {
if (!is_user_logged_in() && is_search()) {
wp_redirect(home_url());
exit;
}
});
102. Prevent Users from Changing Admin Email
add_filter('pre_update_option_admin_email', function($value, $old_value) {
return $old_value; // Prevent changes
}, 10, 2);
103. Automatically Approve Admin Comments
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
add_action('do_feed', function() {
wp_redirect(home_url());
exit;
}, 1);
105. Automatically Log Out Users After a Period
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