What SEO Spam Looks Like in WordPress
SEO spam in WordPress usually appears as hidden links, keyword‑stuffed anchor text, or invisible <iframe> elements that point to low‑quality domains. The spam can be injected into theme files, plugin code, or even stored in the database as rogue posts or options. Common visual clues include:
A sudden surge in outbound links when you view the source of the homepage.
Pages that load extremely slowly because of large hidden
<iframe>blocks.New admin users or scheduled posts that you never created.
Unexpected redirects from your domain to unrelated commercial sites.
In many cases the attacker adds a line like eval(base64_decode('...')) to a core file. That line is the classic backdoor pattern and never belongs in a tutorial snippet. When you see eval() running a base64 string, it is a red flag that the file has been compromised.
The spam may also be stored in the wp_options table as serialized data. Look for option names that contain “spam”, “inject”, or random strings of characters. Open the option value in a text editor; if you see a long base64 string or HTML tags you do not recognize, it is likely malicious.
Another tell‑tale sign is the presence of <script> tags that load JavaScript from domains you have never used. Those scripts often inject additional links after the page loads, which you can spot by disabling JavaScript in the browser and re‑checking the source.
Spam can also hide in image files that have been renamed with a .php extension. Run a file command on all files in wp-content/uploads to ensure they are truly image types; any file reported as “PHP script” should be examined and removed.
Finally, check the WordPress admin dashboard for unfamiliar widgets or menu items. Attackers sometimes add a “SEO Boost” widget that silently adds spam links to every post. If you see a widget you never installed, disable it and look for the underlying code that created it. Recognizing these symptoms lets you target your scans precisely, rather than wasting time on clean areas.
Prepare a Clean Environment Before You Touch the Site
Before you begin any cleanup, you must work from a safe workstation. Make sure the computers you use are free of spyware, malware, and virus infections. Install a reputable anti‑virus scanner and run a full system scan. We cover this step by step in How to remove malware from WordPress, step by step.
Create a full backup of the site—both files and database—so you can revert if needed. Use the command line or your hosting control panel to generate a compressed archive:
# From the site root
tar -czf ~/backups/site-$(date +%F).tar.gz .
mysqldump -u wp_user -p wp_database > ~/backups/db-$(date +%F).sql
Store the backup off‑site, for example in a secure cloud bucket or on a separate physical drive. Verify the backup by listing its contents and opening the SQL dump in a text editor; you should see the full table structure and data without errors.
Next, set the site to maintenance mode so visitors and search engines do not encounter half‑removed spam. You can add a simple .maintenance file in the WordPress root:
<?php
$upgrading = true;
When the file exists, WordPress will display a generic “Briefly unavailable for scheduled maintenance” message. Visit the homepage; you should see that message, confirming maintenance mode is active. When you’re ready to restore normal operation, simply delete the file.
Before making any changes, disable all caching layers on the server. This includes any object caches, page caches, and CDN edge caches. Clear them from the control panel or via WP‑CLI (wp cache flush). Doing this prevents old, infected files from being served while you are editing.
Finally, if you have access to a staging environment, clone the site there and perform all testing on the clone. The staging site should mirror the production database and files, but it runs on a separate URL. After completing cleanup on staging, compare the two sites side by side; identical front‑end output confirms that changes are safe to push live. Use a tool like wget --mirror to capture the live page HTML from both environments and run a diff; no differences means the cleanup did not alter legitimate content.
When you are satisfied that the staging copy is clean, push the cleaned files and database to production using the same tar and mysqldump process in reverse. After deployment, remove the .maintenance file, re‑enable caches, and perform a quick sanity check by loading a handful of key pages in a private browser window. The pages should load without the spam elements you removed earlier.
Scan the Site for Injected Code
WordPress security plugins provide automated scanning, but a manual review is essential for SEO spam. Start with a file‑system scan using grep to locate suspicious patterns:
# Search for eval/base64 patterns in PHP files
grep -R --include="*.php" -nE "eval\(base64_decode|gzinflate|str_rot13" .
The command prints the filename and line number of each match. Any result is a candidate for cleaning. Open each reported file in a secure editor and look for a line that begins with eval(; remove the entire line and save. After editing, run php -l filename.php to ensure the file still parses correctly.
Next, scan the database for hidden links or iframes. Connect with WP‑CLI or mysql and run:
SELECT ID, post_content FROM wp_posts
WHERE post_content LIKE '%iframe%' OR post_content LIKE '%<a%spam%';
If rows are returned, inspect the content in a text editor. Look for long strings of random characters or URLs that you do not recognize. Delete or sanitize the offending markup, then update the post via WP‑CLI (wp post update ID --post_content='cleaned') or the admin editor.
For option tables, run:
SELECT option_name, option_value FROM wp_options
WHERE option_value LIKE '%iframe%' OR option_value LIKE '%<a%spam%';
Again, any matches should be examined. If an option contains serialized PHP data, unserialize it locally, strip out the malicious bits, and re‑serialize before saving.
If the attacker tries to deface your site or add malware, you can also detect these changes by using a web‑based integrity monitor solution. Compare the current HTML output with a known‑good snapshot; differences often reveal hidden spam blocks.
Remember that Malware Scanner (Quick & Standard) is included in every plan, including Free. You can trigger a scan from your hosting dashboard to get a baseline report of infected files.
The free Silent Threads website security checker at /security-checker scans a site from the outside, seeing what any visitor or search engine sees. Run it before and after cleanup to confirm that external observers no longer see the spam.
When the scan finishes, review the list of flagged files. For each file, verify that the path belongs to a core WordPress component, a known plugin, or a theme you have installed. If the path points to a random folder under wp-content/uploads or a mu‑plugin that you never added, delete the file completely rather than editing it. After removal, re‑run the grep command to make sure no more matches appear.
Finally, check server access logs for repeated requests to the malicious URLs you discovered. A sudden spike of 404 or 200 responses for unknown scripts often indicates an active bot probing the site. Blocking those IPs at the firewall level adds another layer of protection.
Identify and Remove the Spam Payload
1. Clean infected PHP files
Locate every file that contains the backdoor pattern identified earlier. Open the file in a secure editor and remove the malicious line. For example, an unsafe version might look like this:
<?php
/* unsafe version */
eval(base64_decode('aW5jbHVkZSB...'));
The corrected version removes the eval line entirely:
<?php
/* cleaned version */
After editing, verify that the file still loads correctly by visiting the page that uses it. No PHP errors should appear, and the page should render as expected. Use the browser console and the server error log to confirm that no “500 Internal Server Error” messages are generated.
If the infected file is part of a core WordPress component, replace it with a fresh copy from the official WordPress release. Download the exact version you are running, unzip, and copy the clean file over the compromised one, preserving file permissions.
2. Purge malicious database rows
For each rogue post or option you identified, delete or sanitize the entry. Using WP‑CLI makes this safe and quick:
# Delete a malicious post by ID
wp post delete 1234 --force
# Update an option to remove injected code
wp option update suspicious_option '' --format=raw
If the spam is stored in serialized data, you may need to unserialize, edit, and re‑serialize the value. A PHP snippet can help:
<?php
$option = get_option('suspicious_option');
$unserialized = maybe_unserialize($option);
unset($unserialized['malicious_key']);
update_option('suspicious_option', maybe_serialize($unserialized));
After running the script, revisit the affected pages; the unwanted links should no longer appear.
3. Fix .htaccess redirects
Attackers often add rewrite rules that redirect visitors to spam domains. Open .htaccess in the site root and look for lines containing RewriteRule that point to external URLs. An unsafe example:
# unsafe version
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^(.*)$ http://spammy-site.com/$1 [R=301,L]
Replace it with the correct WordPress defaults, removing the malicious rule:
# cleaned version
# 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
Save the file and test by visiting the homepage; it should load without redirecting. Use curl -I https://yourdomain.com to confirm that the HTTP status is 200 OK and no Location: header points elsewhere.
4. Remove suspicious options
Some plugins create options that can be abused. Scan wp_options for keys that look random or contain the word “spam”. Delete them with WP‑CLI:
wp option delete random_spam_option
If you are unsure whether an option is used, temporarily set its value to an empty string and monitor the site for errors. If nothing breaks, you can safely delete it later.
After completing all four sub‑steps, run the web‑based integrity monitor again to ensure no hidden payload remains. The monitor should report “No unexpected changes detected”.
Harden WordPress to Prevent Future Spam
Hardening reduces the attack surface and makes it harder for spammers to re‑inject code. Follow the official WordPress Hardening Guide for comprehensive steps, and add these practical measures:
Disable file editing – Add
define('DISALLOW_FILE_EDIT', true);towp-config.php. This prevents attackers from using the theme and plugin editors to add malicious code. After adding the line, revisit the Appearance → Theme Editor screen; you should no longer see the editor interface, confirming that file editing is blocked.Limit PHP execution in uploads – Create an
.htaccessfile insidewp-content/uploadswith:# Prevent PHP execution <FilesMatch "\.(php|php5|phtml)$"> Order Deny,Allow Deny from all </FilesMatch>Once the file is in place, try to access a PHP file that you deliberately placed in the uploads folder via a browser. You should receive a 403 Forbidden response, indicating the rule works.
Enforce strong passwords and two‑factor authentication for all admin accounts. Use a password manager to generate passwords with at least twelve characters, mixed case, numbers, and symbols. Enable a 2FA plugin, then log out and log back in; the login screen will now request a verification code, confirming the extra layer is active.
Install a reputable security plugin that offers firewall rules and login hardening. After activation, navigate to the plugin’s dashboard and enable the firewall. Test the firewall by attempting a known bad request, such as adding
?author=1to a URL; the plugin should block the request and log it.Schedule regular scans using the built‑in Malware Scanner (Quick & Standard) so any new infection is caught early. Run a scan manually first, then set the schedule in the plugin settings. When a scan finishes, the results page should list “No threats detected” if the site is clean.
Additionally, keep WordPress core, themes, and plugins up to date. Enable automatic minor updates by adding:
add_filter( 'auto_update_core', '__return_true' );
to a site‑specific plugin. After saving the plugin file, check the Updates screen; you should see a note that minor updates are automatic.
Finally, restrict file‑system access by limiting the FTP/SFTP user to the wp-content directory only. Verify the restriction by attempting to upload a file outside that directory; the server should reject the operation. By implementing these hardening steps, you raise the barrier for attackers and protect against future SEO spam attempts.
Verify the Cleanup and Monitor Ongoing Activity
After removal, perform a multi‑layer verification:
Front‑end check – View the source of the homepage and key internal pages. Search for
<iframe>or hidden<a>tags that were not there before. If the source no longer contains those elements, the front‑end is clean. Also scan the rendered page with the browser’s “Inspect” tool to ensure no invisible elements are present; the Elements panel should show only the markup you expect.Database audit – Re‑run the SQL queries from the scanning section to confirm no rows match the spam patterns. A clean result set—zero rows returned—means the database no longer stores the malicious markup. To be thorough, run the same queries against the
wp_optionsandwp_postmetatables as well, because some attackers hide payloads in meta values.File integrity – Use the
diffcommand to compare current core files with a fresh WordPress download:diff -qr wp-includes/ wp-includes-clean/When the comparison finishes, you should see only differences in your custom theme or plugin files. Any unexpected core file differences indicate leftover infection. If you notice extra files in the root or
wp-contentthat are not part of any theme or plugin, delete them after confirming they are not legitimate.External scan – Run the free Silent Threads website security checker at /security-checker again. The report should show no external spam links or redirects. The checker displays a list of detected outbound URLs; an empty list confirms that external observers no longer see the spam.
Log monitoring – Review
wp-content/debug.log(if WP_DEBUG_LOG is enabled) for any new PHP errors that could indicate hidden code execution. An empty or error‑free log after a routine visit confirms no hidden code is triggering. Also glance at the server access log for unusual request patterns, such as repeated calls to unknown PHP files.
Set up a cron job to run a quick scan every 24 hours using WP‑CLI:
0 2 * * * /usr/bin/wp core verify-checksums --path=/var/www/html > /dev/null 2>&1
If the checksum verification fails, investigate immediately. The verification command compares each core file against the official checksum list; a mismatch points to a file that has been altered since cleanup.
Finally, keep a weekly snapshot of the site’s file list (find . -type f -printf "%p\n" > filelist.txt) and compare it to a baseline copy. Identical listings week over week show that no new files have been introduced without your knowledge.
Common Mistakes and Troubleshooting
Deleting the wrong database rows – Removing a legitimate post can break navigation. Always export the table before mass deletions and test on a staging copy first. After an export, open the SQL file and verify that only rows matching the spam criteria are selected.
Leaving the backdoor in a cached file – Some hosts cache PHP files. After cleaning, clear all caches (object cache, opcode cache, CDN) to ensure the clean version is served. Verify by disabling the cache temporarily and re‑loading the page; the source should show the cleaned markup.
Changing file permissions incorrectly – Files should be
644and directories755. Overly permissive permissions (777) invite reinfection. Usefind . -type f -exec chmod 644 {} \;andfind . -type d -exec chmod 755 {} \;to reset them, then re‑check withls -l.Relying solely on a single scanner – No scanner catches everything. Run at least two different tools (a plugin scanner and an external service) and compare results.
Forgetting to disable the maintenance mode file – If
.maintenanceremains, visitors will see a blank site. Delete the file after confirming the cleanup is successful. You can confirm removal by visiting the homepage; the normal site should appear without the “Briefly unavailable” notice.
If you encounter persistent spam after following the steps, revisit the scanning phase. Look for missed .php files in rarely used plugins or mu‑plugins directories. Some attackers hide code in image files with PHP tags; run a recursive file command to identify non‑text files that claim to be PHP:
find . -type f -name "*.php" -exec file {} \; | grep -i "php script"
Any anomalies should be examined closely. Open suspicious files in a hex editor if needed; look for <?php tags embedded in what should be binary data.
When you locate a hidden payload, clean it, then rerun the full verification checklist (front‑end source, database audit, file integrity, external scan, and log monitoring). Only when every check reports clean should you consider the issue resolved. Related reading: WordPress Malware Removal Checklist: 10 Steps in Order.




