0

My post revisions are out of control. The issue is that I set the max number in wp-config too late, and some posts must have more than 30+ revisions, while others only have 1-2.

I can prune them all, but I would like to only prune revisions where there are more than 10 revisions on any one post.

Does anyone know a way of doing this?

4
  • 1
    Shouldn't WP automatically be doing this on a semi-regular basis?
    – Tom J Nowell
    Commented Mar 6, 2023 at 19:54
  • @TomJNowell not for any of my sites
    – Matt
    Commented Mar 6, 2023 at 19:56
  • 1
    Have you looked at the WP-Optimize plugin? That's one of the things that it does. And using it doesn't require 'reinventing the wheel'. Plugin page here wordpress.org/plugins/wp-optimize Commented Mar 6, 2023 at 23:23
  • Why do you want to do this? Your databases posts table should handle tens of millions or rows on the posts table so neither disk space nor performance should be impacted by this.
    – Tom J Nowell
    Commented Mar 7, 2023 at 10:02

1 Answer 1

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.