Last updated: November 8, 2026 · Skill level: intermediate
To remove spam links from the WordPress database, export a full backup, search wp_posts, wp_postmeta and wp_comments for hidden links and injected scripts with SELECT queries or wp db search, delete each payload with wp search-replace after a --dry-run, then close the entry point and ask Google to recrawl the cleaned pages.
This guide covers content tables: posts, pages, revisions, synced patterns, template parts, custom fields and comments. If the infection sits in site settings, widgets or autoloaded options, follow our guide on how to check wp_options for malicious entries instead. The two jobs overlap, so plan to run both audits on a hacked site.
- TL;DR: back up, find with SELECT, remove with a dry-run first, delete infected revisions, find the writer, then verify with a live URL Inspection test.
- Tools used: WP-CLI (
wp db export,wp db search,wp db query,wp search-replace), phpMyAdmin or any MySQL client, and Google Search Console.
What does injected spam look like in the WordPress database?
Injected spam is HTML or JavaScript stored in your post content, custom fields or comments that nobody on your team wrote. It usually takes one of four forms: links hidden with CSS, external script tags, invisible iframes, or obfuscated JavaScript that decodes itself in the browser. Visitors rarely notice it. Crawlers and view-source always do.
The scale is real. GoDaddy’s 2024 annual cybersecurity report (published April 8, 2025), built on Sucuri SiteCheck remote scans, logged SEO spam on 422,741 websites, or 38.4% of infections. The same report notes that attackers increasingly store malicious code in WordPress databases instead of files to slip past file-based scanners (GoDaddy, April 2025).
These are the patterns to recognize:
- Hidden link blocks. A
divorspanstyled withdisplay:none,visibility:hidden,font-size:0or a large negative offset, wrapping pharma, casino, loan or escort links. - Off-screen positioning. Sucuri documented injected spam links wrapped in a div styled
position: absolute; bottom: 0px; left: -11055px;so people never see them but crawlers read them (Sucuri, November 23, 2020). That case lived in a core file; the same CSS trick shows up inside post content. - External script tags. A
<script src="https://...">pointing to a domain you do not use, often placed at the very end of the post body. - Invisible iframes. An
<iframe>withwidth="0",height="0"ordisplay:none. - Obfuscated JavaScript. Calls such as
eval(,atob(,String.fromCharCode(,unescape(ordocument.write(, usually around a long encoded string.
A typical hidden-link payload inside post_content looks like this:
<div style="position:absolute;left:-9999px;top:-9999px">
<a href="https://casino-spam.example/">online casino</a>
<a href="https://pills-spam.example/">buy cheap pills</a>
</div>
<script src="https://bad-cdn.example/j.js"></script>
Which database tables should I check for spam links and scripts?
Check wp_posts first. It holds posts, pages, revisions, synced patterns (wp_block), block templates, template parts and navigation menus. Then check wp_postmeta for page-builder data and custom fields, and wp_comments for comment bodies and author URLs. Widgets and site settings live in wp_options and need a separate audit.
Replace wp_ with your real prefix in every query. Run wp db prefix to print it. On multisite, each site has its own tables, such as wp_2_posts for site ID 2 (WP-CLI docs).
| Table and column | What the infection looks like | Detection query (read-only) |
|---|---|---|
wp_posts.post_content (posts, pages) | Hidden link div, external <script>, zero-size <iframe> | SELECT ID, post_type, post_status, post_title FROM wp_posts WHERE post_content REGEXP '<script|<iframe|display: ?none|left: ?-[0-9]{3,}px'; |
wp_posts where post_type = 'revision' | An older copy of the payload that comes back if someone restores that revision | SELECT ID, post_parent, post_modified FROM wp_posts WHERE post_type = 'revision' AND post_content REGEXP '<script|<iframe'; |
wp_posts for wp_block, wp_template, wp_template_part, wp_navigation | Payload inside a synced pattern or header part, so it renders on every page | SELECT ID, post_type, post_title FROM wp_posts WHERE post_type IN ('wp_block','wp_template','wp_template_part','wp_navigation') AND post_content REGEXP '<script|<iframe|display: ?none'; |
wp_postmeta.meta_value | Script or encoded JavaScript inside page-builder data, SEO fields or custom fields | SELECT meta_id, post_id, meta_key FROM wp_postmeta WHERE meta_value REGEXP '<script|<iframe|eval[(]|atob[(]|fromCharCode'; |
wp_comments.comment_content, comment_author_url | Approved comments carrying link lists, scripts or spam author URLs | SELECT comment_ID, comment_post_ID, comment_author_url FROM wp_comments WHERE comment_approved = '1' AND comment_content REGEXP '<script|<iframe|casino|viagra'; |
wp_posts.post_author joined to wp_users | Whole spam posts or pages owned by a user ID that does not exist | SELECT p.ID, p.post_title, p.post_author FROM wp_posts p LEFT JOIN wp_users u ON u.ID = p.post_author WHERE u.ID IS NULL AND p.post_type IN ('post','page'); |
wp_options (widget_block, widget_text, widget_custom_html) | Spam in sidebar or footer widgets | Covered in the wp_options audit guide |
Expect some legitimate hits. YouTube embeds use iframes, analytics snippets live in Custom HTML blocks, and page builders store markup in wp_postmeta. Compare every match against what your team actually added.
How do I back up the database before cleaning it?
Export a full copy with wp db export before you change a single row, move it off the server, and confirm it restores. If you can, clone the site to staging and run every query there first. A careless bulk REPLACE on production, with no backup, can do more damage than the spam itself.
- Export everything:
wp db export pre-cleanup.sql. The command wraps mysqldump and reads credentials fromwp-config.php(WP-CLI docs). - Confirm the table prefix:
wp db prefix. - Download the file and label it as infected. It is your evidence and your rollback, but it still contains the payload, so never restore it as a “clean” backup.
- Prove the backup works before relying on it. Our guide on how to test a WordPress backup before restoring walks through a restore drill.
How do I find spam links with SQL and WP-CLI?
Start broad with wp db search to see which tables and columns contain suspicious markup, then narrow down with SELECT queries through wp db query. Search for markup (script, iframe, display:none), obfuscation functions (eval, atob, fromCharCode) and spam vocabulary. Write down every foreign domain you find, because those domains become your removal targets.
- Get a map of where script tags live.
wp db searchchecks the text columns of your WordPress tables and only prints matches:wp db search '<script' --stats - Look for hiding tricks with a regex:
wp db search 'display: ?none|visibility: ?hidden|left: ?-[0-9]{3,}px' --regex --regex-flags='i' --table_column_once - Search spam vocabulary. Adjust the list to your niche to avoid false positives:
wp db search 'casino|viagra|cialis|payday|replica' --regex --regex-flags='i' --one_line - Pull the affected rows, newest first, so you can see when the injection started.
- Once you know the spam domain, count exactly how many rows carry it in each table. That number is what your cleanup must match.
# Step 4: affected posts, newest first (table: wp_posts)
wp db query "SELECT ID, post_type, post_status, post_modified, post_title FROM wp_posts WHERE post_content REGEXP '<script|<iframe|display: ?none' ORDER BY post_modified DESC"
# Step 5: count rows per table for one known spam domain
wp db query "SELECT COUNT(*) FROM wp_posts WHERE post_content LIKE '%bad-cdn.example%'"
wp db query "SELECT COUNT(*) FROM wp_postmeta WHERE meta_value LIKE '%bad-cdn.example%'"
wp db query "SELECT COUNT(*) FROM wp_comments WHERE comment_content LIKE '%bad-cdn.example%' OR comment_author_url LIKE '%bad-cdn.example%'"
# Or list posts containing the domain through WP_Query
wp post list --post_type=any --s='bad-cdn.example' --fields=ID,post_title,post_status
wp db query does not rewrite table names for you, so the prefix in your SQL must be correct. wp post list --post_type=any skips trashed posts unless you add --post_status=trash (WP-CLI docs), and it does not cover revisions, so keep the SQL checks too.
How do I remove a malicious script from the WordPress database safely?
Remove each confirmed payload with wp search-replace, scoped to the tables you checked, and always run it with --dry-run first. WP-CLI handles PHP serialized data, so it is safe for wp_postmeta where raw SQL is not. For one or two infected posts, a manual edit or a clean revision is faster.
- Dry-run the exact payload against the two content tables. Nothing is saved; you get a report of what would change.
- If the payload varies between posts, switch to a regex. WP-CLI warns that regex mode runs roughly 15 to 20 times slower, so scope it to specific tables.
- Compare the dry-run totals with the counts from your SELECT queries. If they differ, stop and find out why.
- Run the same command without
--dry-run. To review the result before touching the live database, use--export=cleaned.sqlinstead, which writes the transformed data to a file. - Re-run every detection query. Each should now return zero rows.
# 1. Exact string, dry run (tables: wp_posts, wp_postmeta)
wp search-replace '<script src="https://bad-cdn.example/j.js"></script>' '' wp_posts wp_postmeta --dry-run --report-changed-only
# 2. Regex for variants of the same script tag, dry run
wp search-replace '<script[^>]*bad-cdn\.example[^>]*></script>' '' wp_posts wp_postmeta --regex --regex-flags='i' --dry-run
# 2b. Regex for a hidden link div, dry run
wp search-replace '<div style="position:absolute;left:-9999px[^"]*">.*?</div>' '' wp_posts --regex --regex-flags='is' --dry-run
The documented way to replace with an empty value is --old='...' --new='', but WP-CLI marks those two flags as nightly-only for now (wp cli update --nightly). If your stable version rejects an empty second argument, use the nightly flags or edit the rows by hand (WP-CLI search-replace docs). Lazy regex patterns such as .*? can still over-match, so read the dry-run report line by line.
Can I use SQL REPLACE instead of WP-CLI?
Only on columns that never hold serialized PHP, such as wp_posts.post_content and wp_comments.comment_content. Serialized values store each string’s length (s:42:"..."). Shorten the string with raw SQL and the length no longer matches, so PHP cannot unserialize the value and the setting or builder layout is lost. Never run REPLACE on wp_postmeta or wp_options.
Save this as fix.sql, run the SELECT first, then run the file with wp db query < fix.sql or paste it into phpMyAdmin:
-- Table touched: wp_posts (post_content only)
SELECT COUNT(*) FROM wp_posts
WHERE post_content LIKE '%<script src="https://bad-cdn.example/j.js"></script>%';
UPDATE wp_posts
SET post_content = REPLACE(post_content, '<script src="https://bad-cdn.example/j.js"></script>', '')
WHERE post_content LIKE '%<script src="https://bad-cdn.example/j.js"></script>%';
How do I restore a clean revision or delete infected ones?
Revisions live in wp_posts with post_type set to revision and post_status set to inherit. In the block editor, open the Settings sidebar, select the Post or Page tab, click the number next to Revisions, pick a revision from before the injection and click Restore (WordPress.org, updated September 28, 2026). WordPress 7.0 introduced a new revisions screen; the classic side-by-side HTML view is still one click away and is better for spotting injected markup.
Infected revisions stay in the table after you clean the live post. Review them, then delete the ones carrying the payload. The same commands handle whole spam posts and spam comments:
# Revisions of post 123 (table: wp_posts)
wp post list --post_type=revision --post_parent=123 --fields=ID,post_modified
# Delete specific infected revisions or spam posts after review
wp post delete 456 457 --force
# Mark injected comments as spam, or delete them (table: wp_comments)
wp comment spam 789 790
wp comment delete 791 --force
How do I find the entry point so the spam does not come back?
Injected database content always has a writer: a compromised account, a vulnerable plugin, or malicious code on disk. Match the timestamps of infected rows to your access logs, audit privileged accounts, patch or remove plugins with stored XSS flaws, and scan files for backdoors. Skip this and the same links usually reappear within days.
- Build a timeline. Run
SELECT ID, post_title, post_author, post_modified FROM wp_posts WHERE post_content LIKE '%bad-cdn.example%' ORDER BY post_modified;and search your server access logs around those times for POST requests to/wp-admin/post.php,/wp-json/wp/v2/and/wp-admin/admin-ajax.php. If infected posts show old modified dates, the write probably bypassed the editor entirely, which points to direct SQL from a backdoor. - Check who can post scripts. On a single site, Administrators and Editors hold the
unfiltered_htmlcapability, which lets them save JavaScript in posts, comments and widgets; on multisite only Super Admins do (WordPress.org Roles and Capabilities). A script saved under an Author or Contributor account points to a plugin flaw, not a stolen login. - Audit accounts and sessions. Look for administrators you did not create using our guide to find and remove rogue WordPress admin accounts. Then reset passwords, end sessions with
wp user session destroy <user> --all, and rotate keys withwp config shuffle-salts. - Patch stored XSS. Patchstack counted 11,334 new WordPress ecosystem vulnerabilities in 2025, 91% of them in plugins, and the two most exploited entries on its list were unauthenticated stored XSS flaws in LiteSpeed Cache and tagDiv Composer (Patchstack, updated February 25, 2026). Run
wp plugin list --update=availableand update or remove anything outdated. - Rule out file-based re-injection. Run
wp core verify-checksumsandwp plugin verify-checksums --all, then scan with one of the tools in our roundup of WordPress malware removal plugins. - Watch for a week. Re-run
wp db search 'bad-cdn.example' --statsevery day. A match after cleanup means the writer is still active.
How do I check that Google sees the cleaned page?
Use the URL Inspection tool in Search Console and run a live test, because the default result shows Google’s last indexed copy, not the page as it is today. Check the tested page’s HTML for the removed domains. If the Security Issues report lists content or code injection, fix every affected URL, then click Request Review.
- Purge every cache. Clear your page cache plugin, object cache and CDN, or visitors and crawlers keep getting the infected HTML.
- Check the raw HTML yourself. Fetch the page as a normal browser and as Googlebot, since some spam is cloaked so it only appears to crawlers.
- Run a live URL Inspection test. In Search Console, inspect the URL, click Test live URL, then View tested page and read the HTML tab. Google states that the live test fetches the URL in real time, while the default view “is not a live test” (Google Search Console Help).
- Request indexing for key URLs. Requests are subject to a daily limit and do not guarantee reindexing. For many cleaned URLs, submit a sitemap with updated
lastmoddates instead. - Clear the Security Issues report. Google labels spammy links or text added to existing pages “Hacked: Content injection” and malicious code “Hacked: Code injection.” Fix all affected pages, because partial fixes do not earn a partial return, then request a review that explains what you found and removed. Google says a review can take from a few days to a few weeks (Google Search Console Help).
# Normal visitor view
curl -s https://example.com/affected-post/ | grep -iE 'bad-cdn|casino|display: ?none'
# Googlebot user agent, to catch cloaked spam
curl -s -A "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" https://example.com/affected-post/ | grep -iE 'bad-cdn|casino|display: ?none'
Frequently asked questions
These are the questions site owners ask most once they find spam links or injected scripts in their content. Each answer is short and self-contained. For the step-by-step procedure, follow the sections above in order: back up, find, remove, close the entry point, then verify the result in Search Console.
Why can’t I see the spam links on my own site?
Attackers hide them with CSS such as display:none or off-screen positioning, or they show them only to search engine crawlers. View the page source, or fetch it with curl using a Googlebot user agent, to see what crawlers see.
Is it safe to run SQL REPLACE on wp_postmeta?
No. wp_postmeta often holds serialized PHP, and changing a string’s length with raw SQL corrupts it. Use wp search-replace with --dry-run first, because WP-CLI unserializes, edits and reserializes those values for you.
Do I need to delete old revisions after cleaning a post?
Yes, if they contain the payload. Revisions are full copies of the post stored in wp_posts, so anyone who restores an infected revision brings the spam back. Query revisions for the spam domain and delete the matches with wp post delete --force.
Why do spam links come back after I delete them?
Because the writer is still active. A stolen admin login, an unpatched plugin with a stored XSS flaw, or a backdoor file can rewrite your posts after every cleanup. Find and close that entry point, then re-run your detection queries daily for a week.
How long does Google take to clear a hacked content warning?
After you fix every affected page and request a review in the Security Issues report, Google says a review can take from a few days to a few weeks. You get an email when the request is received and another when the review is complete.


Leave a Reply