Skip to content
Tutorials Center
My learning

Topics

Lesson 55 of 68 ยท Forms, Security and Data Handling

Hardening and Securing a WordPress Site

Harden a WordPress site step by step: prepared SQL, nonces, file permissions, updates, wp-config secrets, login limits, 2FA, XML-RPC, backups and plugin risks.

WordPress powers a large share of the web, so it is a constant target for automated attacks. The core software is reviewed heavily and rarely the weak spot. Most real compromises come from three places: outdated plugins and themes, weak or reused passwords, and custom code that skips a security check. Hardening means closing each of those doors and limiting the damage if one still opens.

This lesson is a practical checklist. It ties together everything you learned in this chapter: nonces, sanitizing input, escaping output and capability checks, then adds the server and configuration side. Real WordPress code and server commands are read-only here. The two runnable examples are plain PHP: an audit runner over a sample configuration, and a demonstration of why prepared queries matter.

Layer your defenses

No single setting makes a site secure. Think in layers, so a failure in one is caught by the next:

flowchart TD
    A["Attacker request"] --> B["Network layer<br/>HTTPS, firewall, rate limits"]
    B --> C["Server layer<br/>file permissions, PHP version, isolation"]
    C --> D["WordPress layer<br/>updates, strong logins, 2FA"]
    D --> E["Code layer<br/>capabilities, nonces, escaping, prepare()"]
    E --> F["Recovery layer<br/>tested backups"]

Each layer reduces what an attacker can reach, and backups let you recover when something gets through.

Keep everything updated

Almost every mass-exploited WordPress vulnerability is already fixed in a newer version by the time attacks start. Updating is the single most effective control.

  • Core: minor and security releases install automatically by default. Keep that on.
  • Plugins and themes: enable auto-updates for the ones you trust, review the rest weekly. Delete anything inactive: a deactivated plugin's files can still be reached directly by URL.
  • PHP: run a supported PHP version. Old versions stop receiving security fixes.
  • Only install plugins that are maintained: check the "last updated" date, the active install count and the support forum before you install.
Terminal
wp core check-update
wp plugin list --update=available
wp plugin update --all

These commands come from WP-CLI, covered in WP-CLI.

Protect wp-config.php and secrets

wp-config.php holds your database password and the authentication keys and salts that sign login cookies. Treat it like a private key.

PHP
// wp-config.php (excerpt)
define( 'DB_PASSWORD', getenv( 'WP_DB_PASSWORD' ) ?: '' );

// Unique, random values: generate them with the official salt service or WP-CLI.
define( 'AUTH_KEY',         '...' );
define( 'SECURE_AUTH_KEY',  '...' );
define( 'LOGGED_IN_KEY',    '...' );
define( 'NONCE_KEY',        '...' );
// (and the matching four _SALT constants)

define( 'DISALLOW_FILE_EDIT', true );  // hides the theme/plugin code editor
define( 'FORCE_SSL_ADMIN', true );     // admin and login only over HTTPS
define( 'WP_DEBUG', false );           // never show errors to visitors in production

Useful rules:

  • Never commit real secrets to version control. Read them from environment variables or a file outside the repository.
  • WordPress will also find wp-config.php one directory above the web root, so the file is not downloadable even if PHP stops processing for a moment.
  • Rotating the salts logs every user out, which is what you want after a suspected breach: run wp config shuffle-salts.
  • DISALLOW_FILE_EDIT removes the code editors under Appearance and Plugins. If an attacker gets an admin login, they cannot edit PHP files from the dashboard. DISALLOW_FILE_MODS goes further and blocks installing and updating from the dashboard: use it only if you deploy through version control.
  • Changing the table prefix from wp_ is not a security measure. It only avoids some lazy scripts. Do not rely on it.

File permissions and ownership

On Linux hosting, a sensible baseline is directories 755, files 644, and wp-config.php 640 or 600. The web server user should be able to write only to wp-content/uploads (and to plugin and theme folders if you update from the dashboard). Never use 777.

Terminal
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
chmod 600 wp-config.php

Block PHP execution inside the uploads folder in your web server config. Uploads are meant to hold images and documents, so if a malicious file ever lands there it should not run as code.

Strong logins: passwords, limits and 2FA

The login form (wp-login.php) is attacked constantly with guessed passwords. Three habits defeat most of it:

  1. Unique, long passwords stored in a password manager. WordPress stores only hashes, but your users still choose the passwords.
  2. Two-factor authentication (2FA) for every account that can publish or manage the site. Use a well-maintained 2FA plugin; it hooks into the authenticate filter described in the previous lesson, so it works with the normal login.
  3. Login limiting: lock out an IP or username after repeated failures. A plugin or a web-application firewall can do it, and a host-level tool like fail2ban works too.

Also create a dedicated user for each person, give them the lowest role that lets them work, and delete accounts when people leave. Do not leave a user named admin.

For programmatic access, use application passwords (built into core since 5.6) instead of sharing a real password. Each one can be revoked on its own and works with the REST API.

XML-RPC and other unused doors

xmlrpc.php is an older remote-publishing interface. It is enabled by default and is a common brute-force target, because one request can try many passwords. If you do not use apps that depend on it, turn it off:

PHP
add_filter( 'xmlrpc_enabled', '__return_false' );

You may also want to block direct access to the file at the web-server level, which saves PHP from loading at all. Similarly, consider limiting user enumeration (?author=1 redirects and the /wp-json/wp/v2/users list) if your site does not need to show author names publicly. Treat enumeration limits as a small speed bump, not a defense: the real protection is strong passwords and 2FA.

Code-level security in your plugins and themes

Most plugin vulnerabilities fall into a few repeating patterns. Check your own code against this list before you ship it:

Vulnerability Cause Fix
Missing authorization A handler never calls current_user_can() Check the right capability at the top of every handler
CSRF A state-changing request has no nonce wp_nonce_field() plus check_admin_referer() or wp_verify_nonce()
Cross-site scripting (XSS) Data printed without escaping Escape late with esc_html(), esc_attr(), esc_url(), wp_kses_post()
SQL injection Request data concatenated into SQL $wpdb->prepare() with placeholders
Arbitrary file upload File type and name not validated wp_check_filetype_and_ext(), wp_handle_upload()
Object injection unserialize() on user data Use JSON; never unserialize untrusted input
Open redirect wp_redirect() to a user-provided URL wp_safe_redirect() with an allowed host list

Prepared queries

The real WordPress API for safe SQL is $wpdb->prepare(). It takes a query with %s (string), %d (integer), %f (float) and %i (identifier) placeholders and returns the query with every value correctly escaped and quoted:

PHP
global $wpdb;

$email = isset( $_GET['email'] ) ? wp_unslash( $_GET['email'] ) : '';

$user_id = $wpdb->get_var(
    $wpdb->prepare(
        "SELECT user_id FROM {$wpdb->prefix}myplugin_subscribers WHERE email = %s",
        $email
    )
);

// For a LIKE search, escape the wildcard characters in the value first.
$like  = '%' . $wpdb->esc_like( $term ) . '%';
$rows  = $wpdb->get_results(
    $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE post_title LIKE %s", $like )
);

Never pass a variable straight into the SQL string, even one you "know" is a number. Prefer WordPress APIs such as WP_Query, get_posts() and get_option(), which prepare queries for you. The $wpdb lesson covers the rest of the class.

This example is plain PHP over SQLite. It shows the same attack against a concatenated query and a prepared one. The prepare() here is a small stand-in for the idea; the real one is more thorough and uses the database connection's own escaping.

PHP String concatenation versus a prepared query

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The concatenated query returns every user because the injected quote changed the meaning of the SQL. The prepared version treats the whole input as one string, so it matches nobody.

Audit your configuration

Checklists are most useful when they run automatically. WordPress has a built-in "Site Health" screen that reports many of these items, and tools like WP-CLI and security scanners can check others. The example below is a tiny audit runner: it takes a sample set of configuration values and reports which rules pass. The real wp-config.php is read by WordPress, not by a script like this; the rules are the point.

PHP A configuration audit runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Change a value in $config or $site and run it again. Real tools do the same thing at a larger scale, with rules like these checked against your live environment.

Backups and recovery

A backup is only a backup if you have restored from it. Follow the 3-2-1 rule: three copies, on two kinds of storage, one of them off the server. Back up the database and wp-content (uploads, plugins, themes, mu-plugins). Take one before every major update, and run a restore on a staging copy now and then so you know the process works.

Terminal
wp db export backup-before-update.sql
tar -czf wp-content-backup.tar.gz wp-content

Hosts, backup plugins and managed services can automate this. What matters is that the backups are stored somewhere an attacker with access to the live site cannot delete them.

If you are hacked

Do not just delete the visible malware. Put the site in maintenance mode, change every password (hosting, database, SFTP, admin users), rotate the salts, and compare core files with the official ones using wp core verify-checksums (plugins have a matching wp plugin verify-checksums for plugins hosted on WordPress.org). Restore from a clean backup if you have one, update everything, and find out how the attacker got in: usually an outdated plugin or a stolen password. Otherwise, they will return.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which single habit prevents the most real-world WordPress compromises?

    Most mass attacks use vulnerabilities that already have fixes. The other options are obscurity measures that only slow down lazy scripts.
  2. 2. What does define( 'DISALLOW_FILE_EDIT', true ) do?

    It hides the built-in code editors, so an attacker with an admin login cannot edit PHP files there. DISALLOW_FILE_MODS is the stricter setting that also blocks installs and updates.
  3. 3. A plugin builds a query like "... WHERE email = '$email'" with data from $_GET. What is the fix?

    esc_html() is for HTML output, not SQL. A nonce protects against forged requests but does not stop injection. $wpdb->prepare() escapes and quotes the value for SQL.
  4. 4. Why is a backup you have never restored risky to rely on?

    Only a successful restore test proves the backup contains what you need and that you know the steps.

Summary

  • Security works in layers: network, server, WordPress, code and recovery. A hole in one should be caught by another.
  • Keep core, plugins, themes and PHP updated, and delete unused plugins and themes.
  • Protect wp-config.php, use unique salts, avoid committing secrets, and set DISALLOW_FILE_EDIT and FORCE_SSL_ADMIN.
  • Use sensible file permissions, strong unique passwords, 2FA and login limiting; disable XML-RPC if you do not need it.
  • In code, check capabilities and nonces, escape output, sanitize input and always use $wpdb->prepare() for SQL.
  • Keep tested, off-server backups so a compromise is recoverable.

Next, move from safety to speed: Caching and WP-Cron.