A hacked WordPress site is rarely a single problem. The spam pages, the odd redirect or the red browser warning you can see are the output of the compromise, not the compromise itself. Underneath sit the parts you cannot see: the vulnerability or stolen password that let the attacker in, the small file that lets them come back, and often an extra administrator account or a scheduled task that quietly re-creates whatever you delete. Clean only the visible part and the site looks fine for a day or a week, then the same spam returns. Most failed clean-ups fail for exactly that reason.
So the goal of this guide is not “remove the malware”. It is three jobs in a fixed order. First, stop the damage and keep the evidence. Second, find and close the way in. Third, rebuild every piece of code from sources you trust, then verify that nothing the attacker left behind is still running. The order matters more than any single technique. Change a password before you understand how the attacker got in and they may simply collect the new one. Restore a backup before you copy the infected state and you lose the only record of what happened. Reinstall plugins before you close the vulnerability and you have reinstalled the problem.
The idea that runs through everything below is this: replace code, inspect data. Code on a WordPress site is replaceable. WordPress core, plugins and themes all come from a source you can download again, and your own custom code should live in version control. Data is not replaceable: the database, the uploaded media and the configuration. Attackers hide in both, but you handle them differently. For code, you do not hunt for the bad lines. You throw the whole directory away and put back known-good files, because that is faster and far more reliable than reading thousands of files for something written to look innocent. For data, you cannot throw it away, so you query it, read it and clean it carefully.
Here is how the guide is laid out. You will learn to recognise a real compromise and rule out false alarms, then contain the damage in the first hour without destroying evidence. You will take a forensic copy, rotate credentials in an order that does not hand the attacker a second chance, and work out how they got in by reading file timestamps and server logs. After that comes the actual cleaning: scanning, manual inspection of files and the database, the decision between cleaning, restoring and rebuilding, the reinstall of core, plugins and themes with WP-CLI, and the removal of backdoors, rogue users and scheduled tasks. The last sections cover hardening, asking search engines and blocklists to lift their warnings, the general shape of notification duties, and the review that makes the next incident smaller.
You need three things. You need access to the hosting control panel, ideally with SFTP or SSH as well, because a lot of the work is faster on the command line. You need a computer you trust, since stolen credentials often begin on the machine of the person who logs in. And you need patience: an honest clean-up of a small site is often a matter of hours, a store or a multi-site installation can take days, and rushing the verification steps is how reinfection happens. WP-CLI commands appear throughout and are optional. Every one of them has a point-and-click or file-manager equivalent, and the text says what to look for either way.
A word on what this is and is not. This is general guidance written by WPresident Editorial from public documentation and widely used practice. It is not a forensic service, and hosting setups differ, so read each step before you run it and adapt paths to your server. If the site handles payments or personal data, if you cannot find how the attacker got in, or if the same infection comes back after a rebuild, bring in your host’s security team or a professional incident responder. The section on notification duties is orientation only and is not legal advice.
Key points
- Cleaning a hacked site means closing the entry point and removing every way back in, because deleting visible spam on its own almost always ends in reinfection.
- Copy the infected files, the database and the logs before you change anything, and do the work from credentials and a computer you trust.
- Treat code as replaceable and data as suspect: reinstall core, plugins and themes from official sources, and inspect the database, uploads and configuration by hand.
- A clean scan proves little. A file that should not exist, or that differs from the official copy, is much stronger evidence than any signature match.
- Persistence hides in unglamorous places: must-use plugins, drop-ins, PHP inside uploads, rogue administrators, Application Passwords, WP-Cron events, server cron jobs and SSH keys.
- Rotate credentials twice, once at the outer edge right away and once after the rebuild, because malicious code on the site can capture passwords typed into it.
- Search warnings and blocklists clear only after a review request on a verifiably clean site, and a short post-incident review records the root cause and how long the compromise went unnoticed.
Is the site really hacked? Recognising the signs
Start by deciding whether you have a compromise or a different kind of fault, because the responses are opposite. A broken plugin update, a misconfigured CDN or an expired certificate can all look alarming, and none of them needs an incident response. A real compromise needs containment before any fix. A useful rule of thumb: faults take things away from your site, attackers add things to it.
The noisy signs are the ones people notice first. Visitors get redirected to unrelated sites, sometimes only on mobile, only on the first visit or only when they arrive from a search result, which is why the owner often cannot reproduce it. Pages you never wrote appear, stuffed with pharmaceutical, casino or foreign-language keywords, a pattern often called the pharma hack or the Japanese keyword hack. The home page is defaced. Pop-ups and ads you did not add appear. Browsers show a full-page red warning, search results carry a warning label under your listing, or Google Search Console reports a security issue such as injected content or injected code. Your host may email you about malware, an abuse report or a suspended account, often with a list of flagged files.
The quiet signs matter just as much. Unexplained spikes in CPU or outbound mail suggest the server is being used to send spam or attack others. An administrator account you do not recognise, a plugin you never installed, files with recent timestamps in folders you have not touched, or a settings page that has changed on its own all point the same way. Some compromises are built to stay invisible to you entirely: they show spam links only to search engine crawlers, skim card details at checkout, or sit idle as a stored backdoor waiting for the attacker’s next campaign.
Because the symptoms often depend on who is looking, test like a visitor from outside. Open the site in a private window on a different device and a different network, and also click through from a search result rather than typing the address. Search for your domain together with words like casino, pills or replica and see which pages Google has indexed. Then fetch the page the way a crawler does. These two commands show what a crawler and a search visitor receive, and you are looking for scripts, links or text that your own theme does not produce. Replace example.com with your domain.
$ curl -s -L -A "Googlebot/2.1" example.com | head -n 40
$ curl -s -L -e "google.com" example.com | head -n 40
These checks have limits. Some malware recognises crawlers by network address rather than the user agent string, so a normal-looking response here does not clear you. Search Console’s URL Inspection can fetch a page as Google actually sees it, which is the stronger test.
Before you conclude it is an attack, rule out the common false alarms. Ads or redirects that appear only on your own computer are often a browser extension or malware on that machine. A page that suddenly looks wrong after an update is usually a plugin conflict, which the white screen guide covers. A redirect on one page only may be a legitimate redirect plugin rule. If a third-party script such as an ad or chat widget is the source, the fault is theirs and your files are clean, though you still want to know. When in doubt, treat the site as compromised for the first hour. Containing a site that turns out to be fine costs you a short outage. Ignoring one that is not can cost you customers, rankings and data.
The first hour: contain the damage before you clean anything
The instinct is to start deleting. Resist it for an hour, because the first actions decide whether you can later find the cause, keep your data and avoid harming visitors in the meantime. Containment has a single purpose: stop the site hurting anyone while preserving everything you will need to understand what happened.
Begin an incident log in a plain text file or a shared note. Record the time you noticed the problem, what you saw, who told you, and then every action you take with a timestamp. It feels like overhead until you need it. It lets you reconstruct the sequence for the post-incident review, it shows a client or an insurer what you did and when, and in some jurisdictions the time you became aware of a breach is the moment a notification clock starts. Write down the time zone as well, since server logs are often in UTC.
Contact your host early. Support teams can often see server-level logs you cannot, can tell you whether other sites on the same account are infected, and may already have flagged files. Ask three specific questions: which files did your scanner flag and when, can you give me the raw access and error logs for the last several weeks, and can you isolate or snapshot the account? Ask also whether the host keeps its own backups and how far back they go.
Now take visitors out of harm’s way, and do it at the server rather than inside WordPress. A maintenance-mode plugin only controls what WordPress renders. A backdoor is a separate PHP file with its own address, and it answers requests whether WordPress is in maintenance mode or not. Better options are HTTP basic authentication on the whole site through the hosting panel, an IP allowlist that admits only you, a rule at your CDN or proxy, or the host’s own suspend feature. If you can, return a 503 status with a Retry-After header to everyone else, which tells search engines the outage is temporary. This is a real trade-off for a shop or a business that lives on its traffic, and the right call depends on what the infection is doing. If it redirects visitors to malware, skims payments or sends spam, take the site offline. A short outage costs far less than a customer data incident.
Stop other harm in parallel. If the server is sending spam, ask the host to pause outbound mail. If the site takes payments, disable the checkout or the payment methods, because injected scripts that capture card details at checkout are a known pattern and keep working until the code is replaced. If other websites share the hosting account, treat them as suspect and isolate them too, since a file-writing foothold in one site can reach its neighbours.
Finally, freeze the things that could destroy your good copies. Automatic backup rotation can quietly overwrite the last clean backup with an infected one, so download the oldest and the most recent backups you have and pause deletion where you can. Stop automated deployments and scheduled imports. Do not run mass updates yet: updates are part of the fix, but they also overwrite the files that show how the attacker got in. The evidence copy in the next section comes first.
The first hour, in order
- Start an incident logTimestamp every observation and action from now on.
- Call in the hostAsk for raw logs, account isolation and the list of flagged files.
- Block visitors at the serverBasic auth, IP allowlist or a 503, not just a plugin page.
- Stop outbound harmPause mail, disable checkout, isolate sibling sites.
- Freeze backups and deploysDownload good copies before rotation overwrites them.
- Copy the evidenceFiles, database and logs, stored off the server.
Preserve the evidence: files, database and logs
Before you change a single file, make a complete copy of the site as it stands, infected files and all. The copy has four jobs. It is the raw material for finding the entry point, since timestamps and file contents show what the attacker did. It is the source for any content created since your last good backup, such as orders and comments. It is your proof of what was and was not touched if customers or a regulator later ask questions. And it is your safety net: if a clean-up step goes wrong, you can go back to where you started.
Three things go into the copy: files, database and logs. Run the file copy from the WordPress root directory. Writing the archive into the parent directory keeps it outside the web root, so nobody can download it and it does not try to archive itself. The archive records permissions and modification times, which you will want later.
$ tar -czf ../site-evidence.tar.gz .
Export the database next. The two skip flags tell WP-CLI not to load plugins or themes, so any malicious code inside them does not run while you work. If you do not have WP-CLI, use the export tool in phpMyAdmin or your hosting panel.
$ wp db export ../site-evidence.sql --skip-plugins --skip-themes
Logs are the most perishable evidence. Hosts rotate access logs on a short schedule, and attackers sometimes delete them. Download the web server access and error logs, the PHP error log, and any SSH, SFTP or control-panel login records your host provides, covering as far back as you can get. In a hosting panel they are usually under a logs or metrics heading. On a server you manage yourself they normally sit under the log directory in an nginx or apache2 folder, though paths vary by distribution and setup. Add the host’s own backups to the pile, and take screenshots of everything a visitor, a browser or Search Console currently shows, because warnings change once you start fixing things.
Handle the copy with care. Move the archives off the server to storage you trust, and label them so nobody restores them by mistake, for example by putting the word infected in the file name. Never extract the archive into a web-accessible folder: a web shell inside it would be live the moment it lands there. Never open an infected PHP file in a browser or run it. Do not be alarmed if your antivirus complains when it sees the archive; that is it doing its job on a sample of real malware.
If the site is very large, prioritise. The code folders, the configuration files, the database and the logs matter most. For a huge uploads folder, a file listing with sizes and modification times is more valuable to an investigation than the images themselves, so take that at minimum. If you run a virtual server, a provider-level snapshot of the whole machine is the most complete copy of all and often takes a minute or two.
Rotate credentials in the right order, and do it twice
Stolen or guessed credentials are one of the main ways attackers get in, and they are also what lets an attacker who has been removed walk straight back. Rotating them is non-negotiable. What is rarely explained is the order, and the fact that one round is not enough.
Begin with a computer you trust. If the person who logs in to the site might have malware on their laptop, such as a credential-stealing program, every new password you type on that machine is compromised the moment you set it. Scan it and fix it, or use a different device, before you change anything that matters.
Work from the outside in. The email account used for the hosting and WordPress admin addresses comes first, because anyone with that mailbox can reset every other password. Check it for forwarding rules and filters you did not create, and check its recovery options. Then the domain registrar and DNS, where an attacker can redirect the whole domain or add records that point somewhere else. Then the hosting control panel, then every SFTP and SSH account. Remove accounts you do not recognise, and look for unfamiliar public keys in the SSH authorised keys file, because a key added by an attacker keeps working after every password change. Then the database user and password. When you change the database password you must update the wp-config.php file in the same step or the site fails with a database connection error.
Here is the part most guides skip. Malware on a WordPress site can capture credentials as people type them into it: login code can be modified to log passwords, and a backdoor can read the new database password straight out of wp-config.php. So the second round has to happen after you have rebuilt the code. Before the rebuild, avoid logging in to the WordPress dashboard of the infected site if you can, and do user work from the command line or the database instead. After the rebuild, reset every WordPress user’s password, force everyone to log in again, and rotate the keys.
That last item, the authentication keys and salts in wp-config.php, invalidates every logged-in session when it changes. This matters because a stolen session cookie bypasses the password entirely. Changing them is one command on a site where wp-config.php is writable:
$ wp config shuffle-salts
Do not stop at passwords. Review the Application Passwords section on each administrator’s profile screen and revoke anything you do not recognise, since these are separate credentials for the REST API. Rotate the secrets stored inside the site: payment gateway keys, SMTP and email service credentials, API keys for marketing tools, storage keys used by backup plugins, licence keys for premium plugins, and the connection keys for any remote management dashboard. Finally, look at the accounts that trust the site: Search Console owners, Tag Manager containers, analytics, your CDN and any other dashboard that lists users. Attackers add themselves where they will go unnoticed.
Credential rotation: when, and what to watch for
| When to rotate | What to watch for | |
|---|---|---|
| Email, registrar, DNS | First, from a trusted device | Forwarding rules, recovery options, changed records |
| Hosting, SFTP, SSH | Immediately | Unknown accounts and unfamiliar SSH keys |
| Database password | Immediately, and again after the rebuild | Update wp-config.php in the same step |
| WordPress users and sessions | After the rebuild | Modified login code can capture typed passwords |
| Application Passwords | With the rebuild | Separate REST API credentials on each profile |
| API keys and licences | After the rebuild | Payment, SMTP, backup storage, remote management |
Find the way in: how sites are compromised and how to trace it
If you skip this step you will clean the site and then watch it get hacked again by the same route. Finding the entry point is also the step people skip because it feels like detective work. It is, but it is a structured kind, and even a partial answer changes what you do next.
Attackers reach WordPress sites by a short list of routes. The largest is a known vulnerability in a plugin or theme that has not been updated, or that has been abandoned by its author. Public vulnerability reporting is overwhelmingly about plugins and themes rather than WordPress core, and exploitation of newly disclosed flaws is largely automated, so the gap between a patch being released and your site being scanned can be short. Nulled or pirated copies of premium software are a close second: they are distributed with the backdoor already included. Next come credentials: reused passwords from other breaches, brute force against the login or SFTP, and passwords stolen from an infected computer. Then there are the routes that are not WordPress at all: another site on the same hosting account, a forgotten staging copy or an old install in a subdirectory, a backup archive or database dump left in the web root, an exposed debug log, a database admin tool left on the server. Rarer but real is a supply-chain compromise, where a legitimate plugin is changed after its ownership moves or its developer’s account is taken over.
You infer the route from three clues: where the oldest malicious file sits, what request created it, and what else happened around that moment. Start by listing PHP files changed recently, oldest first. Adjust the 30-day window to match when you think the trouble began, and expect legitimate plugin updates to appear too.
$ find . -type f -name "*.php" -mtime -30 -exec stat -c "%y %n" {} + | sort | head -n 30
Timestamps can be forged, because attackers can set the modification time to match their neighbours. The change time cannot be set directly, which is why a mismatch between the two is itself a lead. Use the stat command on a suspicious file to see both, then take the earliest time and look in the access log around it for requests to that file or, more usefully, to whatever uploaded it. This command lists which paths received POST requests, most frequent first, assuming a standard combined log format where the path is the seventh field.
$ grep '"POST ' access.log | cut -d " " -f 7 | sort | uniq -c | sort -rn | head -n 20
A path you do not recognise, a plugin file that should not accept POST requests, a burst of requests to the XML-RPC endpoint or the login page followed by a success, an upload endpoint hit just before a new file appeared: these are the leads. Then compare the plugin and theme versions that were installed at the time against vulnerability databases. Be honest about the limits. The oldest file you find is rarely the first thing the attacker did, logs may be short or deleted, and time zones differ between servers and your notes. You may end with a ranked list of suspects rather than one culprit. That is fine: patch or remove all of them.
Where did the oldest malicious file appear?
Scan the site, then distrust the result
Scanners are good at one thing: they give you leads quickly. They are poor at giving you a verdict, and mixing up those two roles is how people declare a site clean when it is not. It helps to know what kinds exist and what each can actually see.
Integrity scanners compare the files on your server with known-good copies. Core files can be compared with the official release, and plugins and themes hosted in the WordPress.org repository with their published versions. Security plugins such as Wordfence do this from inside WordPress and can show you a difference or offer to repair a file, and WP-CLI does the same job from the command line, as a later section shows. This is the most trustworthy type of check because it does not depend on recognising the attacker’s code. It only needs to know what the legitimate file looks like. Its blind spot is anything with no official copy: premium plugins, custom code, and files the attacker added that match nothing at all, though an unexpected extra file is itself a finding.
Signature and heuristic scanners look for known malicious strings and suspicious patterns, such as a decoding function wrapped around a request variable. They catch widespread variants quickly and lag behind new ones, and heuristics also flag legitimate code, since plenty of honest plugins use encoding functions. Cloud-based services such as MalCare describe scanning from their own servers to spare yours, and many security suites pair scanning with cleanup and a firewall. Check on each vendor’s page which tier includes cleanup before you plan around it.
Remote scanners such as Sucuri’s SiteCheck request your public pages and report what they serve: injected scripts, blocklist status, signs of outdated software. They are quick and a good independent second opinion on what visitors receive. They cannot see a dormant backdoor in a folder that no public page references, so a clean result means only that the front end looks clean right now. Host-level scanners and command-line tools work on the server side instead. ClamAV is a widely used open-source option whose signatures cover some common web shells but not custom ones.
$ clamscan -r -i wp-content
When you read results, rank each finding by how hard it is to explain innocently. A core or repository plugin file that differs from the official copy is high. A PHP file inside the uploads folder is high. A premium plugin file flagged for a suspicious function is medium: download a fresh copy from the vendor and compare. A generic warning about an old PHP function in a theme is low. Do not delete everything that is flagged, because scanners do flag legitimate code and removing a real core or plugin file by hand can take the site down. Do not click an automatic repair button before your evidence copy exists, either.
Two cautions. A scanner that runs inside the compromised installation depends on code the attacker could have changed. Malware can switch scanners off, hide files from them or feed them false results, so scanning from outside, with a host-level scanner, the command line or a downloaded copy on an isolated machine, is stronger evidence. And a clean report is not a clean bill of health. Treat the scan as the start of the hunt and let the rebuild and the verification steps later in this guide provide the real assurance.

Inspect the files by hand: where attackers hide a way back
Scanner output gives you leads. Manual inspection tells you what is actually there. The principle is to look for what should not exist before you look for what seems evil, because a file that does not belong is a far stronger signal than code that merely resembles malware. The commands below are read-only and run from the WordPress root, so use them before the rebuild to learn what the attacker did and again afterwards to confirm the result.
Start with the one folder that should hold no PHP. Uploads is for media, and the only PHP file normally found there is a tiny placeholder index file.
$ find wp-content/uploads -type f -iname "*.php*"
That pattern also catches double extensions such as image.php.jpg. Depending on how the server is configured, other extensions such as phtml and phar can execute as PHP too, so repeat the search for those. Then look for placeholders that have grown. The silence-is-golden index files are tiny, so one larger than a kilobyte has had something added.
$ find wp-content -type f -name "index.php" -size +1k
Next, the hooks that load without appearing where you normally look. Must-use plugins in the mu-plugins folder run on every request and cannot be deactivated from the plugins screen. Drop-ins are single files in wp-content that WordPress loads for special roles, including object-cache.php, advanced-cache.php and db.php. They are legitimate when a caching plugin or an object cache created them, so ask the same question of each: do I use the feature that explains this file? List the folders directly so nothing hides behind the dashboard.
$ ls -la wp-content wp-content/mu-plugins
Look for hidden files and folders, since a leading dot keeps them out of casual listings, and look at inactive plugins and themes. Attackers favour inactive code because nobody reviews it, yet its PHP files can still be requested directly by anyone who knows the path.
$ find . -mindepth 1 -name ".*" -not -path "./.git*"
Then the files that change how PHP itself behaves. A .htaccess file can redirect visitors who arrive from search engines, and it can also tell the server to run unexpected extensions as PHP, which turns an innocent-looking image into a script. A .user.ini file, which PHP reads in CGI and FastCGI setups, or a php.ini where you can edit one, can set auto_prepend_file or auto_append_file, which runs a chosen file before or after every PHP script on the site, so the malware never has to appear in a WordPress file at all. There can be one of each per directory, so search for all of them.
$ find . -type f -name ".htaccess" -o -type f -name ".user.ini"
Read wp-config.php from top to bottom. Extra include or require lines, code above the database settings and long strings of encoded text do not belong there. Apply the same attention to the first lines of the root index.php and each theme’s functions.php and header.php.
Finally, a content search for decoding and execution functions is a reasonable way to find leads in your own custom code. Expect noise, since many honest plugins use these functions, and treat the hit list as somewhere to look rather than a verdict. The strong signals are an execution function fed by a decoding function, function names assembled from pieces at run time, and single lines thousands of characters long.
$ grep -rlE "(base64_decode|gzinflate|str_rot13)[[:space:]]*[(]" --include="*.php" wp-contentWhere a way back hides, from obvious to subtle
Inspect the database: users, options and injected content
The database is where attackers hide things that survive a full file rebuild, because you cannot simply reinstall it. It also holds the settings that decide who can log in, so it deserves its own pass. Take a fresh export first if anything changed since your evidence copy. The examples assume the default wp_ table prefix, so adjust them if yours differs, and note that multisite installations keep extra tables per site.
Begin with administrators. The Users screen can be made to hide accounts through a filter in malicious code, so query the table directly. This lists every account holding the administrator role, with its registration date.
$ wp db query "SELECT u.ID, u.user_login, u.user_email, u.user_registered FROM wp_users u JOIN wp_usermeta m ON m.user_id = u.ID WHERE m.meta_key = 'wp_capabilities' AND m.meta_value LIKE '%administrator%'"
Every row should be a person you can name, with an email address you recognise. An account registered around the time of the intrusion, or one that is new to you, is a finding. Note any administrator whose email address was changed to a stranger’s, since a hijacked real account looks different from a new fake one.
Next, the settings attackers change to keep access. A classic trick is to switch on open registration and set the default role to administrator, so they can create a fresh account whenever you delete one. Unless you run a membership site, users_can_register should be 0, and default_role should be the least-privileged role you intend, usually subscriber. Check the site address settings too, because a changed value can send visitors elsewhere.
$ wp option get users_can_register --skip-plugins --skip-themes
$ wp option get default_role --skip-plugins --skip-themes
Then look for injected content. This finds posts and pages holding script or iframe tags. Legitimate embeds such as video players will appear, so review each result rather than deleting in bulk. Spam pages created in bulk usually get consecutive IDs, so the second query, which shows the newest rows by ID, is often more revealing than any date field, since dates can be faked.
$ wp db query "SELECT ID, post_type, post_status, post_title FROM wp_posts WHERE post_content LIKE '%<script%' OR post_content LIKE '%<iframe%'"
$ wp db query "SELECT ID, post_type, post_status, post_title, post_date FROM wp_posts ORDER BY ID DESC LIMIT 50"
The options table is the other favourite. A small stub in a file can read a stored payload from an option and run it, which means the visible file looks harmless and the real code lives in the database. Search for decoding and execution functions, and expect false positives from security plugins that store their own detection patterns. Review the custom HTML and text widgets as well, and every plugin that lets you paste scripts into all pages, such as header and footer injectors, snippet managers and tag manager integrations, because their contents live in the database too.
$ wp db query "SELECT option_name FROM wp_options WHERE option_value LIKE '%base64_decode%' OR option_value LIKE '%eval(%'"
Also check which users have created Application Passwords. Any row returned means that account has at least one, and you should open that profile and review them.
$ wp db query "SELECT user_id FROM wp_usermeta WHERE meta_key = '_application_passwords'"
When you clean, prefer targeted edits to bulk operations. For a single injected string repeated across many rows, WP-CLI’s search-replace understands serialised data, which a naive text replacement would corrupt. Always run it as a dry run first and read the count before you remove the flag.
$ wp search-replace 'spam-domain.example' '' --all-tables-with-prefix --dry-runClean in place, restore a backup, or rebuild?
By now you have a picture of what is wrong. There are three ways to reach a clean site, and choosing between them is the biggest decision in the whole process.
Cleaning in place means editing infected files and deleting the extra ones while leaving the rest of the installation as it is. It looks fastest and is the least reliable, because it depends on finding every modification, and one missed backdoor means reinfection. Restoring a backup means swapping in an earlier copy of the site. That helps only if the copy predates the intrusion, and many intrusions begin days or weeks before the first visible symptom. Rebuilding means installing fresh WordPress, plugins and themes from official sources and carrying across only the data you have inspected. It is the most work, and it is the only option where completeness does not depend on how good your detection was.
The rule that makes this manageable is that code is replaceable and data is not. Core, plugins and themes can be put back from official downloads, and your custom code belongs in version control. What you must carry across is the database, the uploads folder and a handful of settings. So even when you restore from a backup, treat the restored files as a source of data rather than as trusted code: take the database and the media, and put the code back from clean sources.
Backups need scepticism. To use one you must show it predates the intrusion, which means returning to the earliest evidence you found when tracing the entry point and picking a backup comfortably older than that. Restore it to an isolated location first and run the file and database checks from earlier in this guide against it. Check where the backups live as well: backup plugins that store archives inside the web root can leak them to anyone who guesses the path, and the archive itself may contain the infection. Finally, a restore onto the same server before you have closed the entry point just hands the attacker the same door.
Newer data decides the rest. A blog that has gained two posts since the backup can be restored and updated by hand. A shop that has taken orders since the backup cannot lose them, so the usual approach there is to keep and clean the current database, inspected as described earlier, rather than restore an old one. Whichever way you go, keep the evidence copy until the post-incident review is done.
Check the uploads folder before you carry it across. Media files should be media files. This lists everything that is not an ordinary image, video, audio or document type. SVG files are deliberately left out of the allowed list because they are XML that can carry scripts, so review them individually. An image with PHP code appended is inert unless some loader includes it, and the loaders are in code you are about to replace, but delete anything unexpected regardless.
$ find wp-content/uploads -type f -not -iname "*.jpg" -not -iname "*.jpeg" -not -iname "*.png" -not -iname "*.gif" -not -iname "*.webp" -not -iname "*.avif" -not -iname "*.pdf" -not -iname "*.mp4" -not -iname "*.mp3"
Last, decide where the clean site will live. A fresh directory on the same account is fine when the account is otherwise clean. If sibling sites were infected, or the account’s SSH keys and cron jobs look tampered with, build on a new account or server and leave the old one blocked until you have taken what you need from it.
Clean, restore or rebuild
Rebuild the code: core, plugins and themes with WP-CLI
This is where the rebuild happens. Before you start, confirm that visitors are blocked, that your evidence copy is off the server, and that you have read wp-config.php, the mu-plugins folder and the drop-ins by hand. WP-CLI loads WordPress to run most commands, which loads wp-config.php and must-use plugins. The skip flags used below leave regular plugins and themes out of the process, but they do not skip those two.
First, see how bad core is. The verify command compares every core file with the checksums that WordPress.org publishes and reports files that differ, files that are missing and extra files inside the core folders. Some warnings are benign, such as a readme.html you removed on purpose, so read each one rather than just counting them. The command does not look inside wp-content.
$ wp core verify-checksums --skip-plugins --skip-themes
Whatever it reports, replace core completely instead of patching single files. A forced download overwrites files but never deletes extra ones, so remove the two core folders first. Run these from the WordPress root, check your location with pwd beforehand, and remember that your evidence copy is what makes the deletion safe.
$ rm -rf wp-admin wp-includes
$ wp core download --force --skip-content
The skip-content flag leaves wp-content alone, and force overwrites the root files such as wp-login.php and index.php. Any PHP file left in the root afterwards, other than wp-config.php, is not part of the WordPress release, so list the directory and justify each one.
Next, wp-config.php. Rather than clean an infected file, start from the wp-config-sample.php that the download just restored. Copy it to wp-config.php, fill in the database name, user, password and table prefix, and add fresh keys and salts. Carry across only custom constants you can explain, one at a time. Anything you cannot explain stays out.
Plugins are cleanest from an empty folder. Move the whole plugins folder out of the web root and recreate it. The database remembers which plugins were active and holds their settings, so you lose very little. Moving files is safer than uninstalling, because deleting a plugin through the dashboard or WP-CLI can run its uninstall routine, and some plugins use that to remove their data.
$ mv wp-content/plugins ../plugins-quarantine && mkdir wp-content/plugins
Then reinstall each plugin you actually use from its official source. For a plugin in the WordPress.org repository, install it by its slug. For a premium plugin, download a fresh zip from the vendor’s account page and install that. Confirm a slug really is the product you run before installing, since a name collision would give you a different plugin. Some plugins keep configuration files inside their own folder, so check the evidence copy for anything to carry over by hand.
$ wp plugin install akismet --activate
$ wp plugin install ../downloads/premium-plugin.zip --activate
Themes follow the same logic. Keep the theme you use, reinstalled from its official or vendor source, plus one default theme as a fallback, and remove the rest. For a child theme or custom code, compare against version control, or read the files, which are usually few and short. Then verify, and update. A plugin you reinstalled at its latest version is the right starting point, but if the vulnerable component has no patched release, replace it with something maintained instead of reinstalling a known problem. If the fresh core is newer than your database expects, WordPress offers a database update when you next open the dashboard, or you can run it yourself now that the configuration is clean.
$ wp core update-db --skip-plugins --skip-themes
Then check the plugins.
$ wp plugin verify-checksums --all
This checks only plugins from the WordPress.org repository, and it will tell you about the ones it cannot check. For those, the fresh vendor download is your assurance.
Rebuilding code from known-good sources
- Verify core checksumsSee what differs, but replace core regardless.
- Remove core foldersDelete wp-admin and wp-includes so extra files cannot survive.
- Download fresh coreForced, with wp-content left alone.
- Rebuild wp-config.phpStart from the sample and keep only settings you can explain.
- Quarantine and reinstall pluginsOfficial or vendor source only, old folder moved out of the web root.
- Prune and reinstall themesThe active theme plus one default fallback.
- Verify, then updateChecksums pass and the vulnerable component is patched or gone.
Remove backdoors, rogue users and scheduled tasks
A rebuild replaces the code you can download again. It does not touch what an attacker placed in your data, in non-WordPress locations or in the account around the site. This section covers those leftovers and how to prove they are gone.
A backdoor is a small piece of code that lets the attacker back in without a password. They are written to look dull and come in a few recurring shapes. The three lines below are patterns to recognise, not code to run. The first executes whatever an attacker sends it. The second calls any function with any argument, which avoids keyword searches. The third includes a file with an image extension that actually contains PHP, which is why a search by file type misses it.
eval(base64_decode($_POST['x']));
$f = $_REQUEST['f']; $f($_REQUEST['a']);
include $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/cache.ico';
Delete such files whole rather than editing out the bad line. A file that exists only as a backdoor has nothing legitimate to preserve, and editing a file you cannot otherwise verify leaves the rest of it unreviewed. Then ask what wrote it, because that is a lead for the entry point.
Next, rogue users. List the administrators from the command line, which sidesteps any filter hiding accounts in the dashboard, and compare each against the people who should have access. Look at editors and authors too, since attackers sometimes create lower roles and escalate later through a plugin flaw. When you delete an account, reassign its content so nothing is deleted with it. The numbers below are examples: 17 is the unwanted user and 1 is a legitimate administrator.
$ wp user list --role=administrator --fields=ID,user_login,user_email,user_registered --skip-plugins --skip-themes
$ wp user delete 17 --reassign=1
Then scheduled tasks. WP-Cron events live in the database and run when visitors arrive. A malicious event with an odd or look-alike hook name can trigger code that downloads a backdoor again after you delete it. After the rebuild, an event whose code no longer exists is harmless, but it still tells you what the attacker intended, so remove it.
$ wp cron event list --skip-plugins --skip-themes
$ wp cron event delete example_hook
WordPress is not the only scheduler. Check the server’s own cron jobs for lines that fetch remote files or run PHP from unusual places, and check the hosting panel for extra FTP and database users, mail forwarders, subdomains and SSH keys you did not create.
$ crontab -l
Automated cleaners, such as the one MalCare advertises, can save time by removing known malware in one pass. Use them as one input, not the final word, since pattern-based removal can leave residue or remove legitimate code. Then prove the result with independent checks.
- Core and plugin checksums pass, and every non-repository plugin is a fresh vendor download.
- No PHP files in uploads, and no unexplained files in the web root, mu-plugins or drop-ins.
- Administrators, options, Application Passwords and cron events all reviewed.
- A second scan by a different tool, plus a crawler-style fetch of the home page.
Open the site again only after those pass. If it is reinfected within hours or days, do not repeat the same clean. Something persistent was missed or the entry point is still open, and the next step is a rebuild on a fresh account.

Harden the rebuilt site so it does not happen twice
Hardening is what turns a clean-up into a recovery. The aim is not an unbreakable site. It is a site where the common routes are closed, a break-in is noticed quickly, and one compromised piece cannot take everything down with it. Think in four layers: prevent, limit, detect and recover.
Prevention starts with updates and a smaller attack surface. Keep core, plugins, themes and PHP current. Delete what you do not use rather than deactivating it. Replace plugins that are abandoned or no longer receive security fixes, and never run nulled software. Vulnerability databases run by services such as Patchstack, Wordfence and WPScan track disclosures so you hear when something you run is affected, and some services add virtual patching, where a firewall rule blocks a known exploit pattern before the code itself is fixed. That buys time. It does not replace the update. Authentication comes next: unique passwords from a password manager, two-factor authentication on WordPress administrators and on your hosting, registrar and email accounts, as few administrators as possible, and separate accounts for daily editing.
Limiting means making a successful attack less useful. Block PHP execution where it does not belong, starting with uploads. On Apache 2.4 this rule goes in a .htaccess file inside the uploads folder. On nginx, a location rule does the equivalent and must appear before the generic PHP handler, because regular-expression locations are matched in order. On managed hosts you often cannot edit server configuration at all, so ask the host to apply the equivalent.
<Files "*.php">
Require all denied
</Files>
location ~* /wp-content/uploads/.*\.php$ { deny all; }
In wp-config.php, one constant removes the dashboard’s built-in theme and plugin code editor, which attackers with a stolen admin session otherwise use to inject code. A stricter constant, DISALLOW_FILE_MODS, also blocks installing and updating from the dashboard, so use it only if you update through WP-CLI or a deployment process.
define( 'DISALLOW_FILE_EDIT', true );
File permissions follow the usual WordPress guidance of 755 for directories and 644 for files, with wp-config.php stricter, commonly 600 or 640 depending on your host. Understand their limit, though. If PHP runs as the same user that owns the files, as it often does on shared hosting, permissions do not stop PHP from writing them. Isolation does that work: one site per account or container, its own database user, and no shared writable folders between sites. A single infected site should not be able to reach its neighbours.
$ find . -type d -exec chmod 755 {} +
$ find . -type f -exec chmod 644 {} +
Detection is what shortens the next incident. Take a baseline of your PHP files after a clean state and compare it on a schedule, then alert on new administrators, plugin installs and file changes. Uptime and content monitors, Search Console email alerts and access logs kept for weeks rather than days all shorten the time between break-in and discovery. Recovery means versioned, off-site backups whose credentials are separate from the site’s, kept longer than an infection is likely to go unnoticed, with a restore tested before you need it.
$ find wp-content -type f -name "*.php" -exec sha256sum {} + | sort -k 2 > ../baseline.sha256
Get search warnings and blocklist flags lifted
A clean site is not the end of the job. Search engines, browsers and other services keep their own records of your site, and they will not forget the warning until you ask them to look again. Do this only once you are confident the site is clean, because a failed review costs time and may lengthen the delay.
Start with the damage in the index. Spam URLs that your cleaned site no longer serves should return a 404 or a 410 status. A 410 says the page is gone for good and is the clearer signal. Do not hide them with a robots.txt rule: that feels tidy but stops crawlers from ever seeing that the pages are gone. Check that your robots.txt and sitemap files are your own, since attackers edit them, and delete any rogue sitemap files they created.
Then check your standing in Search Console. Attackers with access often add themselves as owners, or leave verification files and tags behind, so open the list of owners and users and remove anyone you do not recognise, taking care not to remove the verification method you rely on. Look at the sitemaps section for entries you did not submit. If you were never verified, do that first, because the security report and the review request are available only to verified owners.
The Security issues report lists what Google found, such as hacked content or code injection, with sample URLs. Check those samples yourself, fix every issue, then use the review request and describe in plain words what happened and what you changed. Google documents how long reviews are expected to take, so check its current guidance rather than trusting a figure from anyone else. If a review is rejected, the response shows remaining examples. Fix them before you ask again, because repeated requests on an unfixed site gain nothing. For spam URLs that are already indexed, the Removals tool hides them quickly but only for a limited time, so the 404 or 410 is what makes the change permanent.
Other services keep their own lists. Check the status of your domain in Google’s Safe Browsing site status tool and see which browsers and antivirus vendors flagged it, since aggregator scans show who flagged you and each vendor has its own re-evaluation request. Microsoft’s Bing Webmaster Tools and SmartScreen have their own channels. If the site sent spam, check email blocklists and your sending reputation, confirm your SPF, DKIM and DMARC records are correct, and rotate any mail credentials. If advertising or payment accounts were suspended, they usually need their own review requests too. Your host may need a message before reinstating anything it suspended.
Do not expect a promised timeline. Rankings and traffic often recover after a clean review, but nobody can guarantee when or how fully, and the gap depends on how long the spam stayed indexed. Keep monitoring while you wait.
Notification duties and the post-incident review
Whether you must tell anyone depends on what the attacker could reach and on the laws and contracts that apply to you. WPresident Editorial cannot tell you whether your situation triggers a duty, and nothing here is legal advice. What follows is orientation, so that you ask the right questions early, ideally with a lawyer or a data protection officer.
The key question is what data the site held or processed. A brochure site with no forms holds little. A site with contact forms, a mailing list, user accounts or orders holds personal data: names, email addresses, postal addresses, order history and password hashes. Many jurisdictions treat unauthorised access to personal data as a breach with duties to notify a regulator, the people affected, or both, and they differ on definitions, thresholds and deadlines. The EU and UK GDPR is a well-known example: it generally expects a notifiable breach to be reported to the supervisory authority within 72 hours of the organisation becoming aware, unless the breach is unlikely to risk people’s rights. Other countries and US states have rules of their own. This is why the timestamps in your incident log matter: awareness is typically what starts a clock.
Payments need separate thought. If you use a hosted payment page, your site may never store card numbers, but a script injected into checkout can capture them as customers type, so not storing cards does not settle the question. Your payment provider has incident procedures and contract terms about telling them promptly, so read them and make contact early. Consider also your host, any clients whose contracts require notice if you are an agency, your insurer, whose policy may set strict reporting terms, and, where relevant, law enforcement.
Be careful with what you say publicly. Absence of evidence is not evidence of absence: if logs are missing you cannot honestly say nothing was accessed. State what you know, what you do not, and what you are doing next, and tell users to change passwords they reuse elsewhere.
Then close the loop with a blameless review within a couple of weeks, while memory is fresh. Ask how the attacker got in and whether you can show it. Ask how long passed between the first compromise and the moment someone noticed, and what noticed it. Ask what made the response slow: missing logs, no usable backup, nobody sure who owned the hosting account. Ask which single control would have prevented it or shortened the delay. Turn the answers into a few action items with owners and dates, update your runbook, and share a summary with whoever depends on the site. The aim is a shorter incident next time.
An example recovery schedule
Checklist
- Start an incident log with timestamps and the time zone before you touch anything.
- Contact the host and ask for raw access logs, the list of flagged files and account isolation.
- Block public access at the server level with basic auth, an IP allowlist or a 503, not only a maintenance plugin.
- Disable checkout and outbound mail if the site takes payments or is sending spam.
- Download the oldest and newest backups before automatic rotation overwrites them.
- Save an off-server copy of files, database and logs, labelled infected, and never extract it into a web folder.
- Change email, registrar, hosting, SFTP, SSH and database credentials from a trusted device and remove unknown SSH keys.
- Find the earliest malicious file and match it to access log entries and the component versions installed at the time.
- Run an integrity check and at least one independent scan, and treat the results as leads rather than a verdict.
- Search uploads for PHP files, and inspect mu-plugins, drop-ins, .htaccess, .user.ini and wp-config.php by hand.
- Query the database for administrators, users_can_register, default_role, injected scripts, options holding code and Application Passwords.
- Choose between clean, restore and rebuild, and write down the reason.
- Replace core, plugins and themes from official or vendor sources and rebuild wp-config.php from the sample file.
- Remove rogue users, unexplained WP-Cron events, server cron entries and unknown FTP or database users.
- Rotate WordPress passwords, salts, Application Passwords and stored API keys after the rebuild.
- Confirm core and plugin checksums pass and that a second scanning tool finds nothing.
- Block PHP execution in uploads, disable the file editor, set file permissions and enable two-factor authentication.
- Return 404 or 410 for spam URLs, check Search Console owners and sitemaps, then request a security review.
- Assess notification duties with qualified advice and record each decision with a date.
- Hold the post-incident review, schedule re-scans and keep file-change monitoring running.
Read this next
About this guide. This is general guidance written by WPresident Editorial from documentation and widely used practice. WPresident has not benchmarked the products or methods described. Interfaces and plan limits change, so check the vendor’s current documentation before you act. Not legal, tax or financial advice. See our editorial policy.
Frequently asked questions
How do I know if my WordPress site has been hacked?
Look for redirects, spam pages, browser or search warnings, host notices, administrators you did not create and files that changed without you. Test from another device and network, click through from a search result, and fetch pages the way a crawler does, because many infections hide from the owner. Search Console's security report and your host's scanner are useful second opinions. If you are unsure, treat the site as compromised for the first hour, since containing a false alarm costs far less than ignoring a real one.
Should I take the site offline while I clean it?
Usually yes, at least briefly, and at the server level rather than with a plugin, because backdoors answer requests whether WordPress is in maintenance mode or not. A short outage costs less than visitors being redirected to malware, customers having card details skimmed, or spam being sent from your server. If you cannot take a store offline, at minimum disable checkout and outbound mail. Return a 503 status so search engines treat the outage as temporary.
Can I just restore a backup?
Only if you can show the backup predates the intrusion, and many intrusions begin well before the first visible symptom. Restore to an isolated copy first and run the same file and database checks on it. Close the entry point before restoring onto a live server, or the attacker walks back in through the same door. For shops, restoring a database can lose recent orders, so cleaning the current database is often the better route.
Will a security plugin clean my site automatically?
It can remove known malware and help with integrity checks, and that saves time. It cannot guarantee that every backdoor is gone, and a scanner running inside the infected installation relies on code the attacker may have altered. Treat automated cleanup as one input, then verify with checksums, a manual inspection of uploads, mu-plugins and the database, and a second tool from a different vendor.
Why does my site keep getting reinfected?
Usually one of three reasons. The entry point is still open, for example an unpatched or abandoned plugin or a stolen password. A persistence mechanism survived, such as a file in uploads, a must-use plugin, a rogue administrator, a cron job or an SSH key. Or a neighbouring site on the same account is reinfecting yours. Stop repeating the same clean and rebuild on a fresh account, closing the entry point first.
How long does Google take to remove the hacked warning?
There is no fixed timeline that anyone can promise. After you fix every issue and submit a review request in Search Console's Security issues report, Google reviews the site, and its documentation describes current expectations. A rejected review lists remaining examples, which you must fix before asking again. Warnings in other browsers and antivirus products clear through each vendor's own re-evaluation process.
Do I have to tell my customers or a regulator?
It depends on what data the site held, what the attacker could reach, and the laws and contracts that apply to you. This is not legal advice. Sites with user accounts, forms or orders hold personal data, and many jurisdictions have breach notification rules with their own thresholds and deadlines, so involve a lawyer or data protection officer early. Check your payment provider's incident terms and your insurance policy, and keep your incident log accurate.
I cannot log in to wp-admin. What should I do?
Contain first, then work from outside the dashboard. Use WP-CLI or the database through your hosting panel to look at administrators and reset passwords. Do not rely on the lost-password email if the email account might be compromised. A locked-out dashboard often means an attacker changed your password or removed your account, so check the user list directly. Fix the entry point before you restore access, or the same thing may repeat.
Is deleting the suspicious files enough?
Rarely. The files you can see are the output of the attack, and deleting them leaves the entry point, any backdoors you missed and any changes in the database, cron jobs or accounts. Files you find are leads. Follow them to the entry point, then replace core, plugins and themes from official sources, inspect the data, and rotate credentials. Verification should prove the site is clean, not your failure to find more.
Will being hacked hurt my SEO permanently?
Not necessarily. Spam pages and warnings can damage visibility and traffic while they are live, and recovery usually depends on removing the spam, returning a proper 404 or 410 for the injected URLs and passing a review. How quickly rankings return varies, and nobody can promise a date. The longer the spam stayed indexed and the more links pointed at it, the longer clean-up of the index tends to take.
Should I hire a professional or rely on my host?
Bring in help when the site handles payments or personal data, when you cannot find the entry point, when the infection returns after a rebuild, or when other sites on the account are affected. Your host can often provide logs, isolate the account and run server-side scans, though not every host offers hands-on clean-up. A dedicated incident responder can do forensic work and advise on notification duties. Get a written scope and ask what they will verify.
Can nulled themes and plugins really cause hacks?
Yes. Pirated copies of premium software are a common route, because the distributor can add a backdoor or code that phones home before sharing the files, and you also get no security updates. If your site used one, assume the compromise began there, remove it and buy or replace it with a properly licensed or maintained alternative. Replacing it with another unofficial copy repeats the problem.



