Delete WordPress Post Revisions, With Related Meta and Terms

This snippet will delete WordPress post revisions, along with any related meta and terms. Rather than delete post revisions using a $wpdb query, this uses wp_delete_post which takes care of removing related meta, taxonomy terms, etc.

IMPORTANT NOTE: You should only run this snippet once. There are several ways to make sure of this. Some of the ways include:

  • You can add this to a plugin settings page, and then only run this when clicking a button.
  • You can run this only upon plugin activation.
  • You can set a flag after it runs, then check for that flag to make sure it never runs again. (See bottom of this page for how to implement this example).
  • You could temporarily paste this into your functions.php file, then visit the admin section of your site, which will cause this snippet to run. Then delete the snippet from your functions.php file.
/**
 * Delete WP post revisions
 */
function isa_delete_revisions() {
	// Give this script 5 minutes to run.
	set_time_limit(60*5);

	global $wpdb;
	$revision_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'revision' AND post_name NOT LIKE '%-autosave%'");
	foreach ($revision_ids as $revision_id){
		// This will invoke wp_delete_post, which takes care of related meta, taxonomy terms, etc.
		wp_delete_post_revision($revision_id);
	}
}
add_action('admin_init', 'isa_delete_revisions');

It was mentioned above that the snippet should only be run once, not on every page load. An example follows that will ensure that it only runs once. This example will first check if the snippet has run, and it will only run if it has not run. If the snippet has already run, then it will do nothing.

/**
 * Delete WP post revisions on single install
 */
function isa_delete_revisions() {

	// Run this cleanup only once
	if ( get_option( 'isa_delete_revisions_complete' ) != 'completed' ) {

	    // Give this script 5 minutes to run.
	    set_time_limit(60*5);
	 
	    global $wpdb;
	    $revision_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'revision' AND post_name NOT LIKE '%-autosave%'");
	    foreach ($revision_ids as $revision_id){
	        // This will invoke wp_delete_post, which takes care of related meta, taxonomy terms, etc.
	        wp_delete_post_revision($revision_id);
	    }

		update_option( 'isa_delete_revisions_complete', 'completed' );

	}

}
add_action('admin_init', 'isa_delete_revisions');

See more: ,

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]