Skip to content

WP-CLI bulk content cleanup at scale

Purging tens of millions of spam comments or post revisions with one big DELETE locks the table and brings the site down. Primary-key chunking and WP-CLI loops are the only way through.

You inherit a fifteen-year-old WordPress install with 12 million rows in wp_comments (mostly spam from 2014), 4 million orphan revisions in wp_posts, and an editor who hits Save every minute on a 30,000-word post. The previous operator tried a single DELETE FROM wp_comments WHERE comment_approved = 'spam' during a maintenance window. The table locked, replication lag hit forty minutes, the site returned 503s to logged-in editors, and the run was killed before completion. The spam came back the next week.

What’s happening

DELETE on InnoDB at this scale acquires row locks and writes one undo-log entry per row. With 10M+ rows in a single statement, three things go wrong simultaneously. The undo log grows to gigabytes and forces purge-lag on the primary. The binlog event for that one statement becomes a multi-gigabyte payload that replicas have to apply serially, blocking every other write. And the query holds long enough that any concurrent INSERT on wp_comments from a real visitor either waits or times out — the front-end appears down even though the site itself is fine.

WP-CLI’s wp comment delete and wp post delete translate to individual DELETE statements per ID, which is correct semantically but ten times slower than a chunked SQL approach because each delete fires every comment-meta and post-meta hook. The right pattern is a primary-key range loop: delete by ID range, commit between batches, sleep, then advance the cursor. That keeps the undo log small, gives replicas room to catch up, and lets real traffic continue.

Revision pruning is the same problem with a different table. wp_posts mixes post_type='post', post_type='revision', and post_type='attachment' in one table with one index. A naive DELETE FROM wp_posts WHERE post_type='revision' does a full index scan and locks rows the live site is reading. The revision table also has cascade implications: deleting a revision should clean up its postmeta, and wp_postmeta is one of the largest tables on any mature WordPress install.

How to verify

Measure the damage before you act:

# Count what you're about to delete
wp db query "SELECT comment_approved, COUNT(*) FROM wp_comments GROUP BY comment_approved;"

# Revisions per post type
wp db query "SELECT post_type, COUNT(*) FROM wp_posts GROUP BY post_type ORDER BY 2 DESC;"

# Find the worst offender — single posts with hundreds of revisions
wp db query "SELECT post_parent, COUNT(*) AS rev_count
             FROM wp_posts WHERE post_type='revision'
             GROUP BY post_parent
             ORDER BY rev_count DESC LIMIT 20;"

# Orphan postmeta from already-deleted revisions
wp db query "SELECT COUNT(*) FROM wp_postmeta pm
             LEFT JOIN wp_posts p ON pm.post_id = p.ID
             WHERE p.ID IS NULL;"

If wp_comments is over 5M rows or wp_posts over 2M, do not run any cleanup during business hours. Schedule a low-traffic window and confirm with the site owners.

Estimate the runtime:

# How many comments and how long per 10k batch on this box
time wp db query "SELECT COUNT(*) FROM wp_comments WHERE comment_approved='spam';"
time wp db query "DELETE FROM wp_comments WHERE comment_approved='spam' LIMIT 10000;"

A 10k batch should complete in under two seconds on managed MySQL with a healthy buffer pool. If it takes longer than ten, the buffer pool is undersized for the working set and you should scale the database tier before running the cleanup.

The fix

A primary-key chunker that’s safe for production traffic:

#!/usr/bin/env bash
# wpcli-purge-spam.sh — chunked spam comment purge
set -euo pipefail

BATCH=5000
SLEEP_SECONDS=2
MAX_REPLICA_LAG=10

cd /var/www/wp-site

# Find the highest comment_ID for the cursor
MAX_ID=$(wp db query --skip-column-names \
  "SELECT MAX(comment_ID) FROM wp_comments WHERE comment_approved='spam';")
echo "max spam comment_ID: $MAX_ID"

cursor=0
total_deleted=0

while [ "$cursor" -lt "$MAX_ID" ]; do
  upper=$((cursor + BATCH))

  # Check replica lag before next batch
  lag=$(wp db query --skip-column-names \
    "SHOW REPLICA STATUS\G" 2>/dev/null \
    | awk -F': ' '/Seconds_Behind_Source/ {print $2}' || echo 0)
  if [ "${lag:-0}" -gt "$MAX_REPLICA_LAG" ]; then
    echo "replica lag ${lag}s exceeds ${MAX_REPLICA_LAG}s, pausing"
    sleep 30
    continue
  fi

  # Delete the chunk
  deleted=$(wp db query --skip-column-names \
    "DELETE FROM wp_comments
     WHERE comment_ID > $cursor AND comment_ID <= $upper
       AND comment_approved='spam';
     SELECT ROW_COUNT();")

  total_deleted=$((total_deleted + deleted))
  cursor=$upper
  echo "$(date -Iseconds) cursor=$cursor deleted=$deleted total=$total_deleted"
  sleep "$SLEEP_SECONDS"
done

# Clean up orphan commentmeta
wp db query \
  "DELETE cm FROM wp_commentmeta cm
   LEFT JOIN wp_comments c ON cm.comment_id = c.comment_ID
   WHERE c.comment_ID IS NULL LIMIT 100000;"

echo "done — purged $total_deleted spam comments"

For revisions, the same shape with one extra concern — revision postmeta:

#!/usr/bin/env bash
# wpcli-prune-revisions.sh — keep last N revisions per post, prune the rest
set -euo pipefail

KEEP_PER_POST=5
BATCH=2000
SLEEP_SECONDS=2

cd /var/www/wp-site

# Build the deletion candidate list — revisions beyond KEEP_PER_POST per parent
wp db query "
CREATE TEMPORARY TABLE rev_purge AS
SELECT ID FROM (
  SELECT ID, post_parent,
         ROW_NUMBER() OVER (PARTITION BY post_parent ORDER BY ID DESC) AS rn
  FROM wp_posts
  WHERE post_type = 'revision'
) ranked
WHERE rn > $KEEP_PER_POST;"

TOTAL=$(wp db query --skip-column-names "SELECT COUNT(*) FROM rev_purge;")
echo "revisions to purge: $TOTAL"

# Chunked delete by ID range
MIN_ID=$(wp db query --skip-column-names "SELECT MIN(ID) FROM rev_purge;")
MAX_ID=$(wp db query --skip-column-names "SELECT MAX(ID) FROM rev_purge;")
cursor=$MIN_ID

while [ "$cursor" -le "$MAX_ID" ]; do
  upper=$((cursor + BATCH))

  # Postmeta first, then the revision rows
  wp db query "
    DELETE pm FROM wp_postmeta pm
    INNER JOIN rev_purge rp ON pm.post_id = rp.ID
    WHERE pm.post_id BETWEEN $cursor AND $upper;"

  wp db query "
    DELETE p FROM wp_posts p
    INNER JOIN rev_purge rp ON p.ID = rp.ID
    WHERE p.ID BETWEEN $cursor AND $upper;"

  cursor=$upper
  echo "$(date -Iseconds) cursor=$cursor"
  sleep "$SLEEP_SECONDS"
done

# Optimize the table once at the end — reclaims disk space
wp db query "OPTIMIZE TABLE wp_posts, wp_postmeta;"

Two operational details that matter. First, wp db query runs as the WP-CLI database user, which means binary logging is preserved and replicas will get the changes — exactly what you want for a replicated topology. Second, run both scripts under nohup or tmux and pipe to a log file: a five-million-row purge can take three to four hours on a moderately-sized managed database, and any session interruption is going to be unpleasant. The script is idempotent — re-running it picks up where the last batch committed.

After the bulk delete completes, set define('WP_POST_REVISIONS', 10) in wp-config.php so the problem doesn’t reaccumulate, and install Akismet or an equivalent anti-spam plugin if comments are still open. The chunker is for the one-time historical purge; ongoing pressure needs a different control.


Stack Harbor runs WP-CLI batch operations under the enterprise WordPress hosting operating model with replica-lag guards and rollback points baked into the chunking. If you have a multi-million-row table that someone tried to clean up once and gave up, we can plan the run.