← All posts

The complete guide to cleaning up a WordPress database with WP-CLI (no plugin, no guesswork)

Revisions, auto-drafts, spam, plugin leftovers, orphaned meta, transients: the full process we use to slim down a WordPress database, measuring before acting and always keeping a way back.

WordPress database cleanup with WP-CLI: no plugin, no guesswork

Key points

  • Back up, then measure table by table: a cleanup is only worth doing once you know where the weight is.
  • Revisions, trash and spam go in a few commands; plugin leftovers and orphaned meta need a case-by-case check.
  • Only automate the steps that are unambiguous, and keep the rest as a manual review.

Any WordPress site that has been live for a few years carries data nobody needs any more. Every save created a revision, spam comments piled up, and uninstalled plugins left their settings and sometimes whole tables behind. The site still works, but backups get heavy, migrations drag on and some admin screens slow down. Cleanup plugins promise a one-click fix. On our maintenance work we use WP-CLI, WordPress’s command-line tool, instead: every step is visible, you know exactly what gets deleted, and everything can be replayed or rolled back. Here is the full process, in the order we run it.

Where the bloat comes from

Before deleting anything, know what you’re looking for. The culprits are nearly always the same:

  • Revisions: unlimited by default. A homepage edited weekly for three years ends up with hundreds, each one a full copy of the content.
  • Auto-drafts and trash: WordPress purges them itself, but only if its scheduled tasks actually run.
  • Spam comments: an open comment form attracts thousands, and the anti-spam plugin files them away without ever deleting them.
  • Plugin leftovers: rows in wp_options, custom tables, activity or redirect logs that grow forever.
  • Orphaned meta: rows attached to posts or comments that no longer exist.
  • Expired transients: temporary cache data that never got cleared.

Each category has its own command and, more importantly, its own level of risk. That’s why we never run a blanket cleanup: one category at a time, checking in between.

Step 1: a backup you know how to restore

No exceptions here: no DELETE without a fresh database export. And a backup is only worth something if you can restore it, so have the restore command ready before you start:

# Full, compressed, timestamped backup
wp db export - | gzip > ~/backups/db-$(date +%F-%H%M).sql.gz

# If anything goes wrong: restore
gunzip -c ~/backups/db-2026-11-10-0915.sql.gz | wp db import -

The dash after export streams straight into gzip, so a database of several hundred megabytes doesn’t fill up a shared hosting account with an uncompressed dump. Where we can, we do a site’s first cleanup on a staging copy, see what each command removes, then replay the same sequence on production.

Step 2: find out where the weight is

Cleaning without measuring is deleting at random. Start with the big picture, then drill into tables:

# Quick overview
wp db size --size_format=mb
wp db size --tables

# The 15 heaviest tables, with their (estimated) row counts
wp db query "SELECT table_name AS t,
  ROUND((data_length + index_length) / 1024 / 1024, 1) AS mb,
  table_rows
  FROM information_schema.tables
  WHERE table_schema = DATABASE()
  ORDER BY (data_length + index_length) DESC LIMIT 15"

For InnoDB tables, table_rows is an estimate rather than an exact count, but it’s close enough to spot what’s out of line. Then add a few precise counts:

wp post list --post_type=revision --format=count
wp post list --post_status=auto-draft --post_type=any --format=count
wp post list --post_status=trash --post_type=any --format=count
wp comment list --status=spam --format=count
wp comment list --status=trash --format=count

Write these numbers down: you’ll compare against them afterwards, and they make the report to the client concrete. If wp_posts and wp_postmeta dominate, revisions are the likely cause. If it’s a table named after a plugin, it’s usually a log that never gets pruned. If it’s wp_options, look at transients and plugin leftovers.

Step 3: revisions, trash and auto-drafts

These are the safest deletions, and often the ones that free the most space:

# Revisions, in batches of 100
wp post list --post_type=revision --format=ids | xargs -r -n 100 wp post delete --force

# Posts already in the trash
wp post list --post_status=trash --post_type=any --format=ids | xargs -r -n 100 wp post delete --force

# In wp-config.php
define( 'WP_POST_REVISIONS', 5 );
define( 'EMPTY_TRASH_DAYS', 30 );

Piping through xargs processes IDs in batches and avoids “argument list too long” when there are tens of thousands of them. The two constants don’t delete anything on their own: WP_POST_REVISIONS caps revisions for each post from its next save, and EMPTY_TRASH_DAYS sets how long the trash keeps items. Warn the client before removing existing revisions, in case someone was counting on an old version of a page.

A large number of auto-drafts is a symptom, not the disease. WordPress deletes them after seven days through a daily scheduled event. If thousands remain, WP-Cron isn’t running properly, and that same fault also breaks scheduled posts and automatic updates:

# Is the event that deletes auto-drafts scheduled?
wp cron event list --fields=hook,next_run_relative | grep auto_draft

# Do overdue events actually run?
wp cron event run --due-now

Fix the cause first; the auto-drafts will clear on the next run.

Step 4: spam comments and plugin leftovers

Spam and trashed comments can go without a second thought, along with their meta:

wp comment list --status=spam --format=ids | xargs -r -n 100 wp comment delete --force
wp comment list --status=trash --format=ids | xargs -r -n 100 wp comment delete --force

Plugin leftovers need more care. Find the prefix the removed plugin used (usually a short form of its name), list what matches, actually read the list, then delete:

# Options left by a removed plugin (the pattern accepts the * wildcard)
wp option list --search="oldplugin_*" --fields=option_name,autoload
wp option list --search="oldplugin_*" --field=option_name | xargs -r -n 1 wp option delete

# A custom table: export it on its own before dropping it
wp db export ~/backups/wp_oldplugin_logs.sql --tables=wp_oldplugin_logs
wp db query "DROP TABLE wp_oldplugin_logs"

The classic trap is two plugins with similar prefixes, or a removed plugin whose settings are reused by another one that is still active. Only delete an option when you know what it’s for. For log tables that keep growing (security, redirects, analytics), the real fix isn’t emptying them by hand twice a year but setting a retention period in the plugin itself; most offer one.

Step 5: orphaned meta and expired transients

An orphaned meta row sits in wp_postmeta or wp_commentmeta while its parent no longer exists. A join finds them, but always look at the list of keys before deleting:

P=$(wp db prefix)

# 1. Which keys would be deleted, and how many?
wp db query "SELECT pm.meta_key, COUNT(*) AS nb
  FROM ${P}postmeta pm LEFT JOIN ${P}posts p ON p.ID = pm.post_id
  WHERE p.ID IS NULL GROUP BY pm.meta_key ORDER BY nb DESC LIMIT 20"

# 2. Delete, only once you've checked
wp db query "DELETE pm FROM ${P}postmeta pm
  LEFT JOIN ${P}posts p ON p.ID = pm.post_id WHERE p.ID IS NULL"

# 3. Same idea for comment meta
wp db query "DELETE cm FROM ${P}commentmeta cm
  LEFT JOIN ${P}comments c ON c.comment_ID = cm.comment_id WHERE c.comment_ID IS NULL"

# 4. Expired transients
wp transient delete --expired

Why the extra check? Because we’ve come across plugins that deliberately store global settings with post_id set to 0, and those rows look exactly like orphans. If a key means nothing to you, search the active plugins for it (grep -r "key_name" wp-content/plugins) and exclude it from the query with AND pm.meta_key NOT IN (...) if needed.

One detail saves a false alarm on transients: with a persistent object cache such as Redis or Memcached, transients aren’t stored in the database at all, so the command finding nothing is expected.

Step 6: optimise, verify, write it down

Deleting rows doesn’t necessarily shrink the files on disk. wp db optimize rebuilds the tables to reclaim that space. On a large database it can slow the site for a moment, so run it off-peak.

Then check three things: rerun the step 2 measurements and compare; click through some public pages, the admin and any forms; and watch the PHP error log for the next day. Finally, record what was removed, with before and after numbers. If something odd shows up three weeks later, that note will save you a lot of digging.

Automate what’s safe, and only that

Part of the job can run by itself every month. We only automate the unambiguous steps, always preceded by a backup:

#!/usr/bin/env bash
# wp-cleanup.sh: a deliberately cautious monthly routine
set -euo pipefail
cd /home/account/public_html
mkdir -p ~/backups

wp db export - | gzip > ~/backups/db-$(date +%F).sql.gz

wp transient delete --expired
wp comment list --status=spam --format=ids | xargs -r -n 100 wp comment delete --force

# Keep 60 days of backups
find ~/backups -name 'db-*.sql.gz' -mtime +60 -delete

# Crontab: 4:10 am on the 1st of each month
# 10 4 1 * * /home/account/bin/wp-cleanup.sh >> /home/account/logs/cleanup.log 2>&1

Revisions don’t need to be in there once WP_POST_REVISIONS is set. Orphaned meta, options and plugin tables are deliberately left out: they need a human decision, and a script that deletes blindly will eventually take something that mattered. For an active site, a manual review once or twice a year is plenty.

FAQ

Will this make my site faster?

Not always in a way visitors notice. The clearest gains are in backups, migrations and some admin screens. If the front end is slow, look at autoloaded options, heavy plugin queries or a missing page cache first.

What if I don’t have WP-CLI?

Many hosts offer it over SSH, shared plans included. Failing that, run the SQL from this guide in phpMyAdmin, after exporting the database, using your own table prefix.

Can I just use a cleanup plugin?

You can, but read what each option deletes, back up first, and deactivate the plugin once you’re done. The same caution applies, especially for orphaned meta.

How often should I do this?

With the monthly routine above and the two constants in wp-config.php, a full review once or twice a year is enough for most sites. A site with heavy comment traffic or a busy shop may need closer attention.

Has your WordPress database grown for years with nobody daring to touch it? Our maintenance plans include this cleanup, done carefully, backed by a proper backup, with a written report of what was removed.

Share LinkedIn Facebook X WhatsApp
</>

webtestudio

Web agency: custom WordPress sites, premium themes and SaaS software.

Discuss your project →