Skip to content

Instantly share code, notes, and snippets.

@WPprodigy
Last active July 9, 2020 20:37
Show Gist options
  • Save WPprodigy/d630494df48a4160c188e8c010dd748e to your computer and use it in GitHub Desktop.
Save WPprodigy/d630494df48a4160c188e8c010dd748e to your computer and use it in GitHub Desktop.
<?php
if ( ! class_exists( 'WPCOM_VIP_CLI_Command' ) || ! ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
WP_CLI::add_command( 'vip-remove-old-revisions', 'VIP_Remove_Old_Revisions_Command' );
class VIP_Remove_Old_Revisions_Command extends WPCOM_VIP_CLI_Command {
/**
* Remove a set number of old revisions.
*
* @example wp vip-remove-old-revisions --post-id=123 --revisions-to-keep=500 --dry-run=true
*/
public function __invoke( $args, $assoc_args ) {
$dry_run = true;
if ( isset( $assoc_args['dry-run'] ) && 'false' === $assoc_args['dry-run'] ) {
$dry_run = false;
} else {
WP_CLI::line( 'Processing a dry-run. Must pass --dry-run=false in order to do a live run.' );
}
if ( isset( $assoc_args['post-id'] ) ) {
$post_id = absint( $assoc_args['post-id'] );
} else {
WP_CLI::error( 'Must set a --post-id' );
}
if ( isset( $assoc_args['revisions-to-keep'] ) ) {
$revisions_to_keep = intval( $assoc_args['revisions-to-keep'] );
} else {
WP_CLI::error( 'Must set --revisions-to-keep' );
}
$all_revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) );
$number_to_delete = count( $all_revisions ) - $revisions_to_keep;
$deleted = 0;
if ( $number_to_delete > 1 ) {
$revisions = array_slice( $all_revisions, 0, $number_to_delete );
for ( $i = 0; isset( $revisions[ $i ] ); $i++ ) {
// Skip autosaves.
if ( false !== strpos( $revisions[ $i ]->post_name, 'autosave' ) ) {
continue;
}
$deleted++;
if ( ! $dry_run ) {
wp_delete_post_revision( $revisions[ $i ]->ID );
}
}
}
$message_text = $dry_run ? '%d revisions will be removed.' : '%d revisions have been removed.';
WP_CLI::success( sprintf( $message_text, $deleted ) );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment