Intelligent deletion of WordPress revisions

630 Views Asked by At

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?

1

There are 1 best solutions below

0
adomnom On

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;
}