includes/Database/class-database-cleanup.php
Database Cleanup functionality.
Class Database_Cleanup
Class Database_Cleanup
class Database_CleanupConstants
| Constant | Visibility | Value | Line |
|---|---|---|---|
TABLE_MAP | public | array( \'revisions\' => array( \'posts\', \'postmeta\' ), \'auto_drafts\' => array( \'posts\', \'postmeta\' ), \'trashed_posts\' => array( \'posts\', \'postmeta\' ), \'spam_comments\' => array( \'comments\', \'commentmeta\' ), \'trashed_comments\' => array( \'comments\', \'commentmeta\' ), \'expired_transients\' => array( \'options\' ), \'orphan_postmeta\' => array( \'postmeta\' ), \'unattached_media\' => array( \'posts\', \'postmeta\' ), \'oembed_cache\' => array( \'options\' ), ) | 42 |
MONTH_SECONDS | private | 2678400 | 64 |
FAILED_PURGE_MAX_LIFESPAN | private | 3 * self::MONTH_SECONDS | 80 |
FAILED_PURGE_BATCH_MAX | private | 100 | 92 |
FAILED_PURGE_MAX_ITERATIONS | private | 10 | 100 |
FAILED_PURGE_BUDGET_SECONDS | private | 15.0 | 109 |
FAILED_PURGE_RESERVE_SECONDS | private | 2.0 | 119 |
METHOD_TO_TYPE | private | array( \'clean_revisions_advanced\' => \'revisions\', \'clean_auto_drafts\' => \'auto_drafts\', \'clean_trashed_posts\' => \'trashed_posts\', \'clean_spam_comments\' => \'spam_comments\', \'clean_trashed_comments\' => \'trashed_comments\', \'clean_expired_transients\' => \'expired_transients\', \'clean_orphan_postmeta\' => \'orphan_postmeta\', \'clean_unattached_media\' => \'unattached_media\', \'clean_oembed_cache\' => \'oembed_cache\', ) | 143 |
CLEANUP_METHOD_MAP | public | array( \'revisions\' => \'clean_revisions_advanced\', \'auto_drafts\' => \'clean_auto_drafts\', \'trashed_posts\' => \'clean_trashed_posts\', \'spam_comments\' => \'clean_spam_comments\', \'trashed_comments\' => \'clean_trashed_comments\', \'expired_transients\' => \'clean_expired_transients\', \'orphan_postmeta\' => \'clean_orphan_postmeta\', \'unattached_media\' => \'clean_unattached_media\', \'oembed_cache\' => \'clean_oembed_cache\', ) | 164 |
ACTION_SCHEDULER_TYPE | public | \'action_scheduler\' | 196 |
SALT_KEY | private | \'wppo_db_cleanup_salt\' | 217 |
REMEDIATED_OPTION | public | \'wppo_autoload_remediated\' | 980 |
AUTOLOAD_SIZE_THRESHOLD | public | 1024 | 988 |
AUTOLOAD_CRITICAL_BYTES | public | 819200 | 1003 |
AUTOLOAD_REMEDIATION_LIMIT | public | 100 | 1011 |
AUTOLOAD_THRESHOLD_MIN | public | 100 | 1022 |
AUTOLOAD_THRESHOLD_MAX | public | 10485760 | 1030 |
AUTOLOAD_LIMIT_MAX | public | 500 | 1038 |
EXPORT_LIMIT_MAX | public | 2000 | 1046 |
AUTOLOAD_SIZE_LIMIT_DEFAULT | public | 800000 | 1450 |
Properties
| Property | Visibility | Type | Default | Line |
|---|---|---|---|---|
$health_memo | private static | array|null | null | 127 |
$health_memo_time | private static | float | 0.0 | 135 |
$defer_counts_invalidation | private static | bool | false | 3085 |
publicstatic get_cleanup_method_map()
public static function get_cleanup_method_map(): arrayGet the cleanup method map (type => method).
Return: array<string, — string>.
publicstatic get_valid_cleanup_types()
public static function get_valid_cleanup_types(): arrayGet valid cleanup types including \’all\’.
Return: string[].
privatestatic delete_in_batches()
private static function delete_in_batches(string $select_sql, string $meta_table, string $meta_column, string $main_table, string $id_column, int=1000 $batch): int|falseBatched DELETE helper for post/comment cleanup. Parameter Type Default Description $select_sqlstring— SQL returning a single ID column (must include LIMIT). $meta_tablestring— Fully-qualified meta table name (e.g. $wpdb->postmeta). $meta_columnstring— FK column in the meta table (e.g. post_id). $main_tablestring— Fully-qualified main table name (e.g. $wpdb->posts). $id_columnstring— PK column in the main table (e.g. ID). $batchint=1000— Batch size; matches the LIMIT in $select_sql.
Return: int|false — Number of main rows deleted, or false on SQL error.
publicstatic clean_revisions()
public static function clean_revisions(): int|falseDelete all post revisions from the database.
Return: int|false — The number of rows deleted, or `false` on SQL error.
publicstatic clean_revisions_advanced()
public static function clean_revisions_advanced(=30 $max_age_days, =5 $keep_latest)Remove post revision records older than a computed cutoff while keeping the latest revisions per parent post. Parameter Type Default Description $max_age_days=30— Maximum age in days (clamped to 1-365; audit #1362); revisions older than now – $max_age_days will be eligible for deletion. $keep_latest=5— Number of most recent revisions to retain per parent post.
Return: int|false — Number of rows deleted, or `false` on database error.
privatestatic flush_revision_deletes()
private static function flush_revision_deletes(array $ids, int& $deleted): boolFlush a batch of revision IDs to the database (postmeta + posts) in 50-row chunks. Parameter Type Default Description $idsarray— Revision IDs to delete. $deletedint&— Running deleted counter (passed by reference, incremented).
Return: bool — True on success, false on SQL error.
publicstatic clean_auto_drafts()
public static function clean_auto_drafts()Remove all auto-draft posts and their associated postmeta in batched operations.
Return: int|false — Total number of posts deleted, or `false` on SQL error.
publicstatic clean_trashed_posts()
public static function clean_trashed_posts()Remove all posts with status \’trash\’ and their associated postmeta.
Return: int|false — Total number of posts deleted, or `false` on SQL error.
publicstatic clean_spam_comments()
public static function clean_spam_comments()Delete all spam comments.
Return: int|false — Number of rows deleted, or false on error.
publicstatic clean_trashed_comments()
public static function clean_trashed_comments()Remove trashed comments and their comment meta from the database in batches.
Return: int|false — Number of rows deleted, or false on error.
publicstatic clean_expired_transients()
public static function clean_expired_transients()Delete expired transients and their timeout entries from the options table.
Return: int|false — `int` number of option rows deleted, `false` on SQL error.
publicstatic clean_orphan_postmeta()
public static function clean_orphan_postmeta()Delete orphaned post meta.
Return: int|false — Number of rows deleted, or false on error.
publicstatic clean_unattached_media()
public static function clean_unattached_media()Delete media attachments with no parent post.
Return: int|false — Number of attachments deleted, or false on error.
publicstatic get_autoloadable_values()
public static function get_autoloadable_values(): arrayAutoload values that count as \”autoloaded\” for the options audit.
Return: string[].
publicstatic is_wp_version_at_least()
public static function is_wp_version_at_least(string $version): boolWhether the running WordPress version is at least the given version. Parameter Type Default Description $versionstring— Minimum version (e.g. \’6.6\’).
Return: bool.
publicstatic get_default_autoload_value()
public static function get_default_autoload_value(): stringDefault autoload value for newly created options.
Return: string.
publicstatic get_autoloaded_options()
public static function get_autoloaded_options(int=20 $limit): arrayList the largest autoloaded options, by stored byte size. Parameter Type Default Description $limitint=20— Maximum number of options to return.
Return: array<int, — array{option_name:string,size:int,autoload:string}> Sorted by size.
publicstatic get_core_autoload_options()
public static function get_core_autoload_options(): arrayCore option names that must never have their autoload value flipped.
Return: string[].
publicstatic is_autoload_remediation_supported()
public static function is_autoload_remediation_supported(): boolWhether the runtime supports flipping autoload values (WP 6.6+).
Return: bool.
publicstatic get_autoload_remediation_threshold()
public static function get_autoload_remediation_threshold(=null $settings): intResolve the remediation size threshold from settings with bounds. Parameter Type Default Description $settings=null— Optional settings array or null to load from option.
Return: int — Threshold in bytes.
publicstatic get_autoload_total_bytes()
public static function get_autoload_total_bytes(): intGet the total bytes currently held by autoloaded options.
Return: int — Total bytes, or 0 on error.
publicstatic get_autoload_count()
public static function get_autoload_count(): intGet the number of currently autoloaded options.
Return: int — Count, or 0 on error.
publicstatic get_autoload_critical_threshold()
public static function get_autoload_critical_threshold(): intResolve the critical autoload threshold in bytes.
Return: int — Threshold in bytes (> 0).
publicstatic is_autoload_critical()
public static function is_autoload_critical(?int=null $total, ?int=null $threshold): boolWhether the autoload payload is at or above the critical threshold. Parameter Type Default Description $total?int=null— Optional total bytes (defaults to {@see get_autoload_total_bytes()}). $threshold?int=null— Optional threshold bytes (defaults to {@see get_autoload_critical_threshold()}; pass the already-resolved value to avoid a second filter call).
Return: bool — True when $total >= critical threshold.
publicstatic get_autoload_audit()
public static function get_autoload_audit(int=20 $limit): arraySingle-call autoload audit payload aligned to WP 6.6 semantics. Parameter Type Default Description $limitint=20— Maximum number of options to return.
Return: array{total_autoload_bytes:int,count:int,critical_threshold:int,is_critical:bool,options:array}.
publicstatic get_autoload_parity()
public static function get_autoload_parity(): arrayCompare the reported total against wp_load_alloptions() size.
Return: array{reported:int,alloptions_bytes:int,delta:int,matches_within_rounding:bool}.
publicstatic get_autoload_size_limit()
public static function get_autoload_size_limit(): intGet the Site Health autoloaded-options size limit in bytes.
Return: int — Size limit in bytes.
publicstatic get_autoload_candidates()
public static function get_autoload_candidates(int=self::AUTOLOAD_SIZE_THRESHOLD $threshold, int=self::AUTOLOAD_REMEDIATION_LIMIT $limit): arrayList non-core autoloaded options at or above the size threshold. Parameter Type Default Description $thresholdint=self::AUTOLOAD_SIZE_THRESHOLD— Minimum option size in bytes. $limitint=self::AUTOLOAD_REMEDIATION_LIMIT— Maximum number of candidates to return.
Return: array<int, — array{option_name:string,size:int,autoload:string}> Sorted by size desc.
privatestatic clamp_autoload_threshold()
private static function clamp_autoload_threshold(int $threshold): intClamp a caller-supplied remediation threshold to the supported range. Parameter Type Default Description $thresholdint— Threshold in bytes.
Return: int — Clamped threshold in bytes.
publicstatic plan_autoload_remediation()
public static function plan_autoload_remediation(?int=null $threshold, int=self::AUTOLOAD_REMEDIATION_LIMIT $limit): arrayBuild a dry-run remediation report without changing anything. Parameter Type Default Description $threshold?int=null— Optional threshold override (bytes). $limitint=self::AUTOLOAD_REMEDIATION_LIMIT— Maximum number of candidates.
Return: array{threshold:int,supported:bool,total_autoload_bytes:int,count:int,bytes_saved:int,options:array,backup:array}.
publicstatic get_remediated_options()
public static function get_remediated_options(): arrayGet stored prior autoload values for remediated options.
Return: array<string,string> — Map of option_name => prior autoload value.
privatestatic set_option_autoload_off()
private static function set_option_autoload_off(string $option_name, string=\'no\' $autoload_off): boolFlip one option\’s autoload value off, guarded for WP 6.6+ with legacy fallback. Parameter Type Default Description $option_namestring— Option name. $autoload_offstring=\'no\'— Value disabling autoload (\’off\’ on WP 6.6+, \’no\’ legacy).
Return: bool — True on success, false on failure.
privatestatic restore_option_autoload()
private static function restore_option_autoload(string $option_name, string $prior): boolRestore one option\’s prior autoload value, guarded like the flip path. Parameter Type Default Description $option_namestring— Option name. $priorstring— Prior autoload value to restore.
Return: bool — True on success, false on failure.
publicstatic remediate_autoload()
public static function remediate_autoload(?int=null $threshold, int=self::AUTOLOAD_REMEDIATION_LIMIT $limit): arrayApply one-click autoload remediation: flip candidates to autoload off, one at a time. Parameter Type Default Description $threshold?int=null— Optional threshold override (bytes). $limitint=self::AUTOLOAD_REMEDIATION_LIMIT— Maximum number of options to flip.
Return: array{threshold:int,supported:bool,applied:array,failed:array,bytes_saved:int,total_autoload_bytes:int,backup:array}.
publicstatic revert_autoload_option()
public static function revert_autoload_option(string $option_name)Revert a single remediated option to its prior autoload value. Parameter Type Default Description $option_namestring— Option name to revert.
Return: bool|WP_Error — True on success, WP_Error when unknown/failed.
publicstatic revert_autoload_all()
public static function revert_autoload_all(): arrayRevert all remediated options to their prior autoload values.
Return: array{reverted:string[],failed:string[],restored:array,total_autoload_bytes:int}.
publicstatic export_expired_transients()
public static function export_expired_transients(int=500 $limit): arrayExport expired transients for pre-run review (read-only, expired rows only). Parameter Type Default Description $limitint=500— Maximum number of rows to export.
Return: array<int, — array{option_name:string,timeout_option:string,expired_at:int,size:int}>.
publicstatic clean_oembed_cache()
public static function clean_oembed_cache()Clean oEmbed cache.
Return: bool|int — Number of deleted options or false on error.
publicstatic is_action_scheduler_available()
public static function is_action_scheduler_available(): boolWhether the Action Scheduler store/cleaner API is available.
Return: bool — True when the store + cleaner classes exist.
publicstatic is_action_scheduler_store_available()
public static function is_action_scheduler_store_available(): boolWhether the Action Scheduler store API alone is available.
Return: bool — True when the store class exists.
privatestatic get_action_scheduler_retention()
private static function get_action_scheduler_retention(): arrayResolve the Action Scheduler retention cutoffs using AS\’s own filters.
Return: array{lifespan:int,lifespan_failed:int}.
privatestatic get_action_scheduler_cutoff()
private static function get_action_scheduler_cutoff(int $seconds): ?\\DateTimeBuild a cutoff DateTime N seconds ago via AS when possible. Parameter Type Default Description $secondsint— Age in seconds.
Return: \\DateTime|null — Null when no datetime API is available.
publicstatic get_action_scheduler_health()
public static function get_action_scheduler_health(): arrayQueue health for the Action Scheduler tables (read-only).
Return: array{available:bool,pending:int,failed:int,oldest_pending_age_seconds:int|null,reclaimable:int,reclaimable_bytes:int,total_bytes:int}.
publicstatic reset_action_scheduler_health_cache()
public static function reset_action_scheduler_health_cache(): voidReset the Action Scheduler health memo (test seam).
Return: void.
publicstatic is_failed_action_purge_enabled()
public static function is_failed_action_purge_enabled(): boolWhether the opt-in failed-action purge is enabled.
Return: bool — True when failed actions older than 3 months may be purged.
publicstatic purge_failed_actions()
public static function purge_failed_actions(int=50 $batch_size, bool=true $log, ?float=null $deadline): intPurge failed Action Scheduler actions older than 3 months in batches. Parameter Type Default Description $batch_sizeint=50— Maximum rows deleted per iteration. Default 50, clamped to 1-100. $logbool=true— Whether to write the activity-log row and invalidate the counts cache. Pass false when a wrapper (e.g. clean_action_scheduler()) logs the combined total itself, so one purge emits one row and invalidates once (issue #1310 review). $deadline?float=null— Optional shared wall-clock deadline (microtime(true) value) inherited from a wrapper that already spent part of its budget. Null starts a fresh 15s budget for standalone calls.
Return: int — Number of failed actions deleted.
publicstatic clean_action_scheduler()
public static function clean_action_scheduler(): intPurge terminal Action Scheduler actions past AS retention.
Return: int — Number of actions deleted (0 when AS absent, disabled, or nothing past retention).
publicstatic clean_all()
public static function clean_all()Execute all defined database cleanup routines and collect their results.
Return: array<string, — int|WP_Error> Associative array keyed by cleanup type (e.g. \’revisions\’, \’auto_drafts\’) with each value set to the number of rows deleted or a `WP_Error` instance if that cleanup failed.
publicstatic get_revision_defaults()
public static function get_revision_defaults(=null $settings)Get revision cleanup defaults. Parameter Type Default Description $settings=null— Optional settings array or null to load from option.
Return: array{0:int,1:int} — Tuple of [max_age_days, keep_latest].
publicstatic auto_clean()
public static function auto_clean($settings)Execute configured database cleanup routines according to provided settings. Parameter Type Default Description $settingsarray— Cleanup settings. Recognized keys: – \’dbRevMaxAge\’ (int) Maximum age in days for revision pruning (default 30). – \’dbRevKeepLatest\’ (int) Number of latest revisions to retain per parent (default 5).
Return: string[] — List of methods that failed.
publicstatic get_counts()
public static function get_counts()Get current counts for each database cleanup category.
Return: array<string,int> — Associative array mapping cleanup type to its current count.
publicstatic invoke_cleanup_method()
public static function invoke_cleanup_method($method, ... $args)Call a static cleanup method by name and convert a `false` result into a `WP_Error`. Parameter Type Default Description $methodmixed— The static method name to invoke (string; other types are guarded). $args...— —
Return: mixed — The invoked method\’s return value, or a `WP_Error` if the method returned `false` or is not callable.
publicstatic reset_runtime_state()
public static function reset_runtime_state(): voidReset per-blog cleanup health and deferral memos.
Return: void.
publicstatic invalidate_counts_cache()
public static function invalidate_counts_cache(): voidInvalidate the DB cleanup counts cache by incrementing the salt or deleting the transient.
Return: void.
publicstatic on_post_change()
public static function on_post_change($post_id, ?\\WP_Post=null $post): voidCallback for save_post/deleted_post to invalidate DB cleanup counts for public post types. Parameter Type Default Description $post_idint— Post ID. $post?\\WP_Post=null— Post object.
Return: void.
privatestatic get_tables_size()
private static function get_tables_size(array $tables): intGet the combined size (data + index) of several database tables in bytes. Parameter Type Default Description $tablesarray— Full table names (including prefix).
Return: int — Combined size in bytes, or 0 if unknown.
privatestatic get_table_size()
private static function get_table_size(string $table): intGet the size (data + index) of a database table in bytes. Parameter Type Default Description $tablestring— Full table name (including prefix).
Return: int — Table size in bytes, or 0 if unknown.
publicstatic optimize_table()
public static function optimize_table(string $table): boolRun OPTIMIZE TABLE on a given table to reclaim disk space and rebuild indexes. Parameter Type Default Description $tablestring— Unprefixed table identifier (e.g. \’posts\’, \’postmeta\’).
Return: bool — True on success, false on invalid identifier, empty table, skipped due to size (>1GB), or query failure.
publicstatic maybe_optimize_tables()
public static function maybe_optimize_tables(array $table_names, bool $enabled): voidConditionally optimize a list of unique database tables. Parameter Type Default Description $table_namesarray— Unprefixed table identifiers (e.g. \’posts\’, \’commentmeta\’). $enabledbool— Whether optimization is enabled.
Return: void.
Hooks
Hooks referenced in includes/Database/class-database-cleanup.php: Hook Type Line Notes wppo_revisions_time_budgetfilter 384 — wppo_unattached_media_time_budgetfilter 790 — wppo_core_autoload_optionsfilter 1148 @param ×1 wppo_autoload_critical_thresholdfilter 1282 @param ×1 wppo_purge_failed_actionsfilter 2424 @param ×1 wppo_action_scheduler_cleanup_enabledfilter 2602 @param ×1 wppo_database_cleanup_completedaction 2694 @param ×2 wppo_database_cleanup_completedaction 2709 — wppo_database_cleanup_completedaction 2712 —