Elegantly prune post revisions

WordPress will trim revisions on a post when creating new revisions, this is how it does it at the end of wp_save_post_revision:


    // If a limit for the number of revisions to keep has been set,
    // delete the oldest ones.
    $revisions_to_keep = wp_revisions_to_keep( $post );

    if ( $revisions_to_keep < 0 ) {
        return $return;
    }

    $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );

    $delete = count( $revisions ) - $revisions_to_keep;

    if ( $delete < 1 ) {
        return $return;
    }

    $revisions = array_slice( $revisions, 0, $delete );

    for ( $i = 0; isset( $revisions[ $i ] ); $i++ ) {
        if ( false !== strpos( $revisions[ $i ]->post_name, 'autosave' ) ) {
            continue;
        }

        wp_delete_post_revision( $revisions[ $i ]->ID );
    }

It should be easy to wrap that in a function that takes a $post argument and put it in a WP_Query loop or a CLI command, or just a trim revisions button