Delete post revisions on post publish

I think a small plugin with the hook ‘publish_posts’ is enough. But I dont know about a core function to delete revisions and I use a query with WP functions. The source is untested, written only for this post.

<?php
/**
 * Plugin Name: WPSE71248 Delete Revisions on Publish Posts
 * Plugin URI:  http://wordpress.stackexchange.com/questions/71248/
 * Description: 
 * Version:     1.0.0
 * Author:      Frank Bültge
 * Author URI:  http://bueltge.de
 * License:     GPLv3
 */

! defined( 'ABSPATH' ) and exit;

add_action( 'publish_post', 'fb_remove_revisions' );

function fb_remove_revisions( $post_id = FALSE ) {

    $post_id = (int) $post_id;

    $revisions="";
    // Get the revisions
    $revisions = new WP_Query( array(
        'post_status'    => 'inherit',
        'post_type'      => 'revision',
        'showposts'      => -1,
        'posts_per_page' => -1,
        'post_parent'    => $post_id
    ) );

    if ( empty( $revisions ) )
        return $post_id;

    // Remove the revisions the non-core-way
    global $wpdb;
    foreach ( $revisions->posts as $revision ) {
        $query = $wpdb->prepare(
            "
            DELETE FROM $wpdb->posts 
            WHERE ID = %d
            AND post_parent = %d
            ",
            $revision->ID, 
            $post_id
        );
        $wpdb->query( $query );
    }

    return $post_id;
}

Alternative use the download from Gist 4017151

Leave a Comment