Trim Old Revisions, Keeping the Latest (WP-CLI)
Adds a "wp trim-revisions" command that deletes old revisions but keeps the newest few for every post. It only reports what it would delete until you add --yes.
Opens WPIDE on
Code
if ( ! defined( 'WP_CLI' ) || ! WP_CLI ) {
return;
}
WP_CLI::add_command( 'trim-revisions', function ( $args, $assoc_args ) {
global $wpdb;
$keep = max( 0, (int) ( $assoc_args['keep'] ?? 5 ) );
$confirm = ! empty( $assoc_args['yes'] );
// Only parents that have more revisions than we keep.
$parents = $wpdb->get_col( $wpdb->prepare(
"SELECT post_parent FROM {$wpdb->posts} WHERE post_type = 'revision' GROUP BY post_parent HAVING COUNT(*) > %d",
$keep
) );
$total = 0;
foreach ( $parents as $parent_id ) {
$revisions = wp_get_post_revisions( (int) $parent_id, array( 'orderby' => 'date ID', 'order' => 'DESC', 'fields' => 'ids' ) );
$old = array_slice( $revisions, $keep );
$total += count( $old );
if ( $confirm ) {
foreach ( $old as $revision_id ) {
wp_delete_post_revision( $revision_id );
}
}
}
if ( $confirm ) {
WP_CLI::success( sprintf( 'Deleted %d revisions from %d posts, keeping %d each.', $total, count( $parents ), $keep ) );
} else {
WP_CLI::log( sprintf( '%d revisions in %d posts would be deleted (keeping %d each). Add --yes to delete them.', $total, count( $parents ), $keep ) );
}
}, array(
'shortdesc' => 'Deletes old post revisions, keeping the newest ones.',
'synopsis' => array(
array( 'type' => 'assoc', 'name' => 'keep', 'optional' => true, 'default' => 5, 'description' => 'Revisions to keep per post.' ),
array( 'type' => 'flag', 'name' => 'yes', 'optional' => true, 'description' => 'Actually delete. Without it the command only reports.' ),
),
) );
Notes
Example "wp trim-revisions --keep=3 --yes"; take a database backup first, deleted revisions cannot be restored.
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.