Secure a WordPress site is not just about installing plugins—it also requires implementing coding best practices to prevent vulnerabilities. Since WordPress is a widely used CMS, it has become a common target for cyber threats. To How to secure a WordPress site, developers can enforce strong authentication, sanitize inputs, restrict unauthorized access, and implement security headers. Writing secure code, disabling XML-RPC, limiting login attempts via functions, and using nonces for form validation are crucial steps.
Keeping WordPress core, themes, and plugins updated also reduces security risks. In this guide, we will explore coding techniques and best practices to harden your WordPress site, ensuring a safe and resilient web application.4
Table of Contents
Essential Security Measures to Protect Your WordPress Site
Use Strong Login Security
✔️ Enable Two-Factor Authentication (2FA) (e.g., Google Authenticator, Wordfence Login Security).
✔️ Change the default “admin” username to something unique.
✔️ Use strong passwords (uppercase, lowercase, numbers, and special characters).
✔️ Limit login attempts to prevent brute-force attacks (use the “Limit Login Attempts Reloaded” plugin).
Keep Everything Updated
✔️ Regularly update WordPress core, themes, and plugins.
✔️ Delete unused themes and plugins (they can be security risks).
✔️ Use only trusted plugins from the WordPress repository.
Steps For How to Secure a WordPress Site
Step 1: Prevent Direct Access to wp-config.php file
Do you guys know about the wp-config.php file? If you are a Backend WordPress Developer then you should know about this File! This File is a secret key of every Website. Suppose in your house there are lots of precious things so you will store things in a box then you will lock that. Then you will carefully keep that Key so just like that this file is the Secret Key of the Website. It stores Database Credentials.
So, We need to secure this file first. Write this below code into .htaccess file in your theme.
<files wp-config.php>
order allow,deny
deny from all
</files>
PHPStep 2: Restrict Admin Area Access by IP
Next Come, Our Wp-admin Portion. In WordPress theme there are three folders ->
- Wp-admin
- Wp-content
- wp-include
We should make sure anyone can not be able to access the wp-admin Folder.
In case, if you have a static IP, you can limit admin access only to your IP.
<Files wp-login.php>
order deny,allow
deny from all
allow from YOUR_IP_ADDRESS
</Files>
How to Secure a WordPress SiteAdd this to your .htaccess file also. This is For “Restrict Admin Area Access by IP“.
Step 3: Disable File Editing in wp-admin
By default, WordPress allows users to change on wp-admin file. WDisable File Editing in wp-admin.
define('DISALLOW_FILE_EDIT', true);
define('DISALLOW_FILE_MODS', true);
PHPAdd this code to your wp-config.php File.
Step 4: Prevent User Enumeration (Hacker Enumeration Attack)
Attackers often use enumeration to find valid usernames by trying URLs like /?author=1
. Because For the user the id is 1, 2 or something. So prevent this, we need to add code in the functions.php file.
function disable_author_archives() {
if (is_author()) {
wp_redirect(home_url());
exit;
}
}
add_action('template_redirect', 'disable_author_archives');
PHPStep 5: Limit Login Attempts to Prevent Brute Force Attacks
We all WordPress developers know that WordPress provides multiple login attempts. There is no restriction. If we give a restriction that will be good!
function limit_login_attempts($user, $username, $password) {
$max_attempts = 5;
$lockout_time = 30 * 60; // 30 minutes
$ip = $_SERVER['REMOTE_ADDR'];
$attempts = get_transient('login_attempts_' . $ip);
if ($attempts === false) {
$attempts = 0;
}
if ($attempts >= $max_attempts) {
return new WP_Error('too_many_attempts', 'You have been locked out. Try again later.');
}
$attempts++;
set_transient('login_attempts_' . $ip, $attempts, $lockout_time);
return $user;
}
add_filter('authenticate', 'limit_login_attempts', 30, 3);
PHPMultiple logins a common for all types of Websites.
Step 6: Auto-Logout Inactive Users
Imagine, on your website, there are multiple logged-in users because of some reason. After a time we should Change the Password and also add a custom code for this like:
function auto_logout_users() {
echo '<script>
var timeout = 600000; // 10 minutes
setTimeout(function(){ window.location.href = "' . wp_logout_url() . '"; }, timeout);
</script>';
}
add_action('wp_footer', 'auto_logout_users');
PHPStep 7: Hide WordPress Version to Prevent Targeted Attacks
When a hacker comes to our website they try to figure out the version of PHP, WordPress, and so on. So they can find vulnerabilities and attack the site easily. The best Practice will be to Hide your WordPress version from the functions.php file.
function remove_wp_version() {
return '';
}
add_filter('the_generator', 'remove_wp_version');
PHPStep 8: Disable Directory Browsing
This prevents hackers from viewing file contents in your directories. write the below line in .htaccess file.
Options -Indexes
PHPStep 9: Force Secure Cookies
Force WordPress to use HTTPS cookies and protect user sessions.
define('FORCE_SSL_ADMIN', true);
define('COOKIE_SECURE', true);
define('COOKIE_HTTPONLY', true);
PHPStep 10: Change the Prefix of Database Table
When we store the data in the WordPress table by default WordPress uses the WP_ prefix for the table. It will be good if you can change that prefix.
$table_prefix = 'bitlevelcode_';
PHPStep 11: Prevent Unauthorized Query Parameter Login
There is a WordPress function name with “wp_set_auth_cookie“. If somehow hackers access the functions.php file of your site then they can use this function for login to wp-admin. They will use this function and a query parameter suppose the query parameter is a hacker.
They will pass that query parameter to the URL like this “https://example.com/?hacker=1”. We need to prevent that also!
remove_action('init', 'wp_set_auth_cookie'); // Prevent direct execution
function secure_auth_cookie($cookie_user) {
if (!is_user_logged_in()) {
wp_die('Unauthorized Authentication Attempt.');
}
}
add_action('set_auth_cookie', 'secure_auth_cookie', 10, 1);
PHPwp-config.php file
if (!is_admin()) {
remove_action('init', 'wp_set_auth_cookie');
}
PHP.htaccess file:
<FilesMatch "\.(php|php\.)$">
deny from all
</FilesMatch>
PHPDisable Execution of PHP Files in wp-content/uploads. Hackers often upload malicious PHP files via the media uploader.
step 12: Scan for Suspicious Code Automatically
🔹 Solution: Create a PHP File Scanner (Upload this script to your server and run it)
function scan_for_malicious_code($dir) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file !== "." && $file !== "..") {
$path = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
scan_for_malicious_code($path);
} else {
$content = file_get_contents($path);
if (strpos($content, 'wp_set_auth_cookie') !== false && strpos($path, 'functions.php') !== false) {
echo "Suspicious code found in: " . $path . "\n";
}
}
}
}
}
scan_for_malicious_code(__DIR__);
PHPIf you want to know about malicious attacks you can visit this site.
Related Posts:
>>How to use Ajax in WordPress?
Conclusion: How to Secure a WordPress Site
Securing a WordPress website requires a combination of best practices, coding techniques, and security tools. By implementing strong authentication, sanitizing inputs, restricting unauthorized access, and using security plugins, you can significantly reduce risks. Regularly updating WordPress core, themes, and plugins helps prevent vulnerabilities, while enforcing security headers and disabling unnecessary features like XML-RPC adds extra protection. Additionally, setting up firewalls, limiting login attempts, and using nonces for form validation ensure safer interactions. A well-secured WordPress site not only protects data but also enhances user trust. By following this article “How to Secure a WordPress Site “, and these coding and security measures, you can safeguard your website from potential cyber threats and maintain a stable, secure online presence.