2

I want to clean up my WordPress database and delete some post revisions.

But I only found plugins or code to delete all revisions. But this is not, what I want. I want to keep revisions with major changes. That means only revisions saved within a short time period should be deleted. If the last revision date is not within a certain time period, it should not be deleted.

E.g. I wrote a post a year ago and created 3 revisions. Half a year later I edited something and again created 4 revisions. The intelligent cleanup I'm looking for should clean the 2 older revisions when creating the post and the 3 when editing it. Only the last changes should remain.

The logic could be: Only delete the revision before the current revision, if it's not older than a week.

Is there a plugin out there or a code, that does such an intelligent clean up of revisions?

woltis
  • 31
  • 5
  • 1
    It's 2019 and I have this same desire. I have a page with a huge number of revisions (let's say 100), and every time I attempt to save the page I get some 500 error; I'm hitting a server limit of some kind. After manually deleting 20 oldest revisions one-by-one, and taking a few minutes to do so, I can save without any error. This workflow I've done 10 times and it's going to be this way for awhile. Instead I would like to be able to, with one click, "delete revisions older than X". – Kalnode Feb 10 '19 at 18:20

1 Answers1

3

I see three options here:

1. Don't fret!

Databases are designed to deal with a vast amount of information very efficiently. You're bound to make significantly bigger performance savings by profiling your themes / plugins, or uninstalling unnecessary plugins.

2. Limit number of revisions allowed

There's an awesome filter called 'wp_revisions_to_keep' that you can tack into to restrict revisions per post. It's not an ideal solution, but it's a quick one.

add_filter('wp_revisions_to_keep', function() { return 10; });

Or you could use this in wp-config.php for the same effect:

define( 'WP_POST_REVISIONS', 3 );

3. Clear revisions as you go

Before a new revision is created, a check is done to ensure the new version is different to the old one. This uses the 'wp_save_post_revision_post_has_changed' filter (no official docs available for this one).

We can tap into this hook to update the existing one instead.

add_filter( 'wp_save_post_revision_post_has_changed', 'minimize_revisions' );

function minimize_revisions( $hasChanged, $lastRevision, $newRevision ) {
    if( !$hasChanged ) return false;

    $revisionTimeThreshold = 60 * 60 * 24; // One day
    $now = get_the_time('U');

    if( $now - strtotime($lastRevision->post_date) < $revisionTimeThreshold ) {

        // Update revision, rather than create a new one
        $newRevision->ID = $lastRevision->ID;
        wp_update_post($newRevision);
        return false;
    }

    return true;
}
adomnom
  • 564
  • 2
  • 9