Performance PHP Intermediate

Delete Old Post Revisions Automatically

Remove post revisions older than 90 days with a daily scheduled task, keeping the database lean without losing recent history.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 20 lines
add_action( 'init', function (): void {
	if ( ! wp_next_scheduled( 'nahnu_delete_old_revisions' ) ) {
		wp_schedule_event( time(), 'daily', 'nahnu_delete_old_revisions' );
	}
} );

add_action( 'nahnu_delete_old_revisions', function (): void {
	$old = get_posts( [
		'post_type'      => 'revision',
		'post_status'    => 'inherit',
		'posts_per_page' => 200,
		'fields'         => 'ids',
		'no_found_rows'  => true,
		'date_query'     => [ [ 'column' => 'post_modified_gmt', 'before' => '90 days ago' ] ],
	] );

	foreach ( $old as $revision_id ) {
		wp_delete_post_revision( $revision_id );
	}
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Every time you save a post, WordPress stores a full copy as a revision. On busy sites that adds up to tens of thousands of rows. Limiting revisions stops new ones piling up; this snippet clears out old ones.

How it works

Once a day, a scheduled task finds up to 200 revisions last modified more than 90 days ago and deletes them with wp_delete_post_revision(), which also removes their meta. Working in batches keeps each run quick; a big backlog clears over a few days.

Revisions from the last 90 days stay, so you can still undo recent changes.

Things to watch

  • Deleted revisions can’t be restored. Take a backup before the first run if you’re unsure.
  • Combine with “Limit Post Revisions Globally” so fewer revisions are created in the first place.

How to test it

Run the task straight away with WP Crontrol, or wp cron event run nahnu_delete_old_revisions, then check an old post: revisions older than 90 days should be gone.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only