Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.