# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Developer](https://wpide.com/library/category/developer/)
- Tags: wp-cli, revisions, database
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/cli-trim-revisions/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Trim Old Revisions, Keeping the Latest (WP-CLI)" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
