Auto-Drafts and Trash Cleanup Tool
Adds Tools > Clean Up Drafts and Trash with counts of leftover auto-drafts, trashed posts and trashed or spam comments, and a button to remove them all permanently after confirmation.
Opens WPIDE on
Code
add_action( 'admin_menu', function () {
add_management_page( 'Clean Up Drafts and Trash', 'Clean Up Trash', 'manage_options', 'wpide-trash-cleanup', function () {
global $wpdb;
$day = gmdate( 'Y-m-d H:i:s', time() - DAY_IN_SECONDS );
if ( isset( $_POST['wpide_clean_trash'] ) && check_admin_referer( 'wpide_clean_trash' ) && current_user_can( 'manage_options' ) ) {
$posts = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE ( post_status = 'auto-draft' AND post_date_gmt < %s ) OR post_status = 'trash' LIMIT 300", $day ) );
$comments = $wpdb->get_col( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_approved IN ('trash','spam') LIMIT 500" );
foreach ( $posts as $id ) {
wp_delete_post( (int) $id, true );
}
foreach ( $comments as $id ) {
wp_delete_comment( (int) $id, true );
}
printf( '<div class="notice notice-success"><p>%s</p></div>', esc_html( sprintf( 'Deleted %d post(s) and %d comment(s). Run again if more remain.', count( $posts ), count( $comments ) ) ) );
}
$counts = array(
'Auto-drafts (older than a day)' => (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'auto-draft' AND post_date_gmt < %s", $day ) ),
'Trashed posts and pages' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_status = 'trash'" ),
'Trashed comments' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_approved = 'trash'" ),
'Spam comments' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->comments} WHERE comment_approved = 'spam'" ),
);
echo '<div class="wrap"><h1>Clean Up Drafts and Trash</h1><table class="widefat striped" style="max-width:520px"><tbody>';
foreach ( $counts as $label => $count ) {
printf( '<tr><td>%s</td><td>%s</td></tr>', esc_html( $label ), esc_html( number_format_i18n( $count ) ) );
}
echo '</tbody></table><form method="post" onsubmit="return confirm(\'Permanently delete these items?\');">';
wp_nonce_field( 'wpide_clean_trash' );
submit_button( 'Delete permanently', 'primary', 'wpide_clean_trash', true, array_sum( $counts ) ? array() : array( 'disabled' => 'disabled' ) );
echo '</form></div>';
} );
} );
Notes
Auto-drafts are empty placeholders WordPress creates when you open the editor; they are safe to delete once they are a day old.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.