Skip to main content
KadiCache
Browse 37 Docs Guides & Search

Safe Database Cleanup, Action Scheduler Hygiene & Automated Schedules

Clean post revisions, auto-drafts, trash, expired transients, orphaned metadata, and completed Action Scheduler logs in bounded cursor batches while protecting WooCommerce orders.

Support/DatabaseCleanup.phpSupport/DatabaseCleanupItems.phpCli/DatabaseCli.php
WP Admin -> KadiCache -> Database
MODULE 33 · 2X RETINA
Bounded-batch Database Cleanup with live category counts, revision retention cap, and automated scheduling.2880×1840 WebP
Quick Summary · 30-Second Operational SpecSource-Verified Guide
WP Admin Path
WP Admin -> KadiCache -> Database
Expected Outcome
8 Safe Cleanup Categories · Bounded Cursor Batches · 0 Order Data Risk
Key Marker / Engine
DatabaseCleanup.php | DatabaseCleanupItems.php | DatabaseCli.php
  • Cleans 8 targeted bloat categories (revisions, auto_drafts, trash_posts, trash_comments, spam_comments, transients, actions, orphans) in bounded primary-key cursor batches—never locking InnoDB tables.
  • Hardcoded eCommerce & Editor Protections (DatabaseCleanupItems.php): Explicitly excludes shop_order*, shop_subscription, edd_payment, attachment, order_note comments, open editor post locks (postLocked), and your latest $keep revisions per post.
  • Safe Action Scheduler Hygiene: Deletes only aged complete (> 7d), canceled (> 7d), and failed (> 30d) rows via ActionScheduler::store()->delete_action() after rechecking live_claim and recent_log—never touching pending or in-progress jobs!
  • Includes an Itemized Confirmation Modal, Last Cleanup Run Receipt Table, automated schedules, and --dry-run WP-CLI inspection.

Why Unchecked WordPress & WooCommerce Databases Slow Down Over Time#

While Early PHP Delivery serves anonymous readers in ~14 ms with 0 SQL queries, your MySQL / MariaDB database still powers every logged-in wp-admin save, WooCommerce /checkout/ transaction, inventory lookup, and cache-miss build. Over 12 to 24 months on an active store, three tables silently balloon into millions of dead rows:

  1. wp_actionscheduler_actions & wp_actionscheduler_logs: WooCommerce Subscriptions, webhooks, marketing syncs, and SEO plugins log tens of thousands of complete, canceled, and failed background tasks every month.
  2. wp_posts & wp_postmeta: Saving a 4,000-word landing page 60 times creates 60 full HTML copies (revision rows) plus orphaned _elementor_data / custom-field postmeta rows whose parent posts were deleted long ago.
  3. wp_options Expired Transients: Plugins that set temporary transients without reading them again leave thousands of expired _transient_timeout_* rows sitting inside wp_options.

KadiCache Free Core (DatabaseCleanup.php and DatabaseCleanupItems.php) cleans all eight categories safely inside WP Admin -> KadiCache -> Database without running dangerous DELETE ... JOIN table-locking queries.

FIG 01Viewing the 4-KPI telemetry strip, Safe Quick Clean preset, revision retention cap, and live candidate counts across all 8 categoriesZoom 2x

Complete Reference: All 8 Cleanup Categories & Built-In Safety Guards#

Every single cleanup category in DatabaseCleanupItems.php enforces strict age, post-type, and ownership rechecks immediately before deletion:

Category Key (--items)UI Label in Database TabExact Safety Guard Enforced in DatabaseCleanupItems.php
revisionsPost revisionsKeeps the newest database_keep_revisions revisions per parent post; skips trashed parents, active editor autosaves (wp_is_post_autosave + postLocked), and all shop_order* / shop_subscription / edd_payment types; deletes via core wp_delete_post_revision()
auto_draftsAuto-draftsDeletes only auto-draft rows older than 7 days that are not open/locked in an editor and contain zero WooCommerce order_note comments
trash_postsTrashed postsRespects EMPTY_TRASH_DAYS retention window, skips locked posts and order/payment post types, and deletes via wp_delete_post($id, true)
trash_commentsTrashed commentsRespects trash retention age and explicitly excludes comment_type = 'order_note' so WooCommerce order audit trails are never touched!
spam_commentsSpam commentsRemoves comment_approved = 'spam' (excluding order_note) cleanly via wp_delete_comment($id, true)
transientsExpired transientsDeletes only expired _transient_timeout_* (and _site_transient_timeout_* when authorized) where timeout < $started; automatically skips DB scan when an external persistent object-cache.php manages transients in RAM!
actionsAction Scheduler recordsTouches only complete (> 7 days), canceled (> 7 days), and failed (> 30 days) rows—rechecking live_claim IS NULL and recent_log = 0 right before calling ActionScheduler::store()->delete_action()!
orphansOrphaned metadata & relationshipsRemoves bounded batches (<= 1,000 postmeta/commentmeta, <= 200 term_relationships) where post_id > 0 and NOT EXISTS reconfirms no parent row was created mid-run
FIG 02Reviewing exact candidate row counts and revision retention rules before starting a background cleanup runZoom 2x

Bounded Cursor Batching, Confirmation Modal & Post-Run Receipt#

Running a giant DELETE FROM wp_postmeta query on a live store locks MySQL for 45 seconds and causes checkout 504 Gateway Timeout errors. KadiCache prevents that completely:

  1. 1-Click Safe Quick Clean Preset: Selects low-risk everyday hygiene categories while keeping your configured revision retention count intact.
  2. Itemized Pre-Run Confirmation Modal: Before a single row is deleted, KadiCache displays exact candidate counts per category and active retention safeguards.
  3. Primary-Key Cursor Background Batches (WHERE ID > %d ORDER BY ID LIMIT ...): Cleanup executes asynchronously in bounded background slices with zero OFFSET scan degradation and zero table locks.
  4. Detailed Last Cleanup Run Receipt Table: Logs the exact timestamp, status pill, processed batch count, elapsed duration, and proportional row breakdown per category for full auditability.
FIG 03Auditing removed row counts, processed batches, elapsed time, and category share inside WP Admin -> KadiCache -> DatabaseZoom 2x
BASHInspecting & Running Safe Database Cleanup via WP-CLI
# 1. Inspect live candidate counts across all 8 categories (0 deletions)
wp kadicache db status --format=table

# 2. Dry-run specific categories first in CI / SSH
wp kadicache db clean --items=revisions,transients,actions --dry-run

# 3. Queue bounded background cleanup for selected categories
wp kadicache db clean --items=revisions,auto_drafts,spam_comments,transients,actions

For active WooCommerce catalogs and multi-author blogs, keeping 3 to 5 recent revisions per post alongside Weekly scheduled cleanup of auto_drafts, spam_comments, transients, and completed actions keeps wp_posts and wp_actionscheduler_logs lean year-round while giving content editors plenty of undo history. On WordPress Multisite installations, DatabaseCleanupItems::canCleanSiteTransients() restricts network wp_sitemeta transient cleanup strictly to the main site under Super Admin, WP-CLI, or cron contexts so subsite admins never touch shared network tables.

Frequently Asked Operational Questions

Can Database Cleanup ever delete a WooCommerce order, subscription, or customer order note?
Never. DatabaseCleanupItems::postTypes() explicitly excludes shop_order*, shop_subscription, edd_payment, and attachment types, and every post/comment query explicitly excludes comment_type = "order_note".
Will cleaning Action Scheduler records cancel pending WooCommerce subscription renewals or active webhooks?
Never! Only completed (> 7 days old), canceled (> 7 days old), and failed (> 30 days old) rows with zero active claim_id and zero recent log entries are eligible. Pending and running jobs are 100% untouched.
What happens if an editor is actively writing a draft while scheduled Database Cleanup runs?
DatabaseCleanupItems checks WordPress post edit locks (postLocked) and skips auto-drafts newer than 7 days—so active editing sessions and autosaves are completely protected.
Can an AI assistant run database cleanup without my permission via MCP?
No! In KadiCache’s AI MCP server, clean_database is classified under the destructive scope and strictly requires an explicit single-use administrator approval token (ap_...) before queueing any deletion.
How often should I schedule automatic Database Cleanup?
Weekly scheduled cleanup (keeping 3 to 5 recent revisions per post) is ideal for active WooCommerce stores and editorial blogs.
Gergis — Lead Systems & Cache Architect
Principal WordPress & Cloud Edge Architect
E-E-A-T Source Verified

Creator of KadiCache’s Early PHP Drop-In, 7-Driver Object Cache Engine, Cloud Remove Unused CSS, and Zero-CLS Lazy Render pipeline.

apps/wordpress-plugin/src/Support/DatabaseCleanup.phpapps/wordpress-plugin/src/Support/DatabaseCleanupItems.phpapps/wordpress-plugin/src/Cli/DatabaseCli.php
Was this engineering guide helpful?