Create a Custom Function to Limit Post Revisions in WordPress

Emily S Dec 19, 2024 Post Management
How can I stop my WordPress site from saving too many versions of my posts?
What is the best way to limit the number of post revisions in WordPress using custom code?
Andy answered Dec 19, 2024

Limiting Post Revisions in WordPress

Custom Code Solution

Add this code to your theme's functions.php file or in a site-specific plugin to limit post revisions:

This code sets a maximum number of revisions for posts:

define('WP_POST_REVISIONS', 5);

For more control, this function lets you set different limits for different post types:

function limit_post_revisions($num, $post) {
    $post_types = array(
        'post'    => 5,  // Regular posts: 5 revisions
        'page'    => 3,  // Pages: 3 revisions
        'product' => 2   // WooCommerce products: 2 revisions
    );
    
    return isset($post_types[$post->post_type]) 
        ? $post_types[$post_type] 
        : 5; // Default for other post types
}
add_filter('wp_revisions_to_keep', 'limit_post_revisions', 10, 2);

To completely disable revisions for specific post types:

function disable_revisions_for_post_types() {
    remove_post_type_support('post', 'revisions');
    remove_post_type_support('page', 'revisions');
    // Add more post types as needed
}
add_action('init', 'disable_revisions_for_post_types');

Clean Existing Revisions

This function removes old post revisions from the database:

function clean_old_revisions() {
    global $wpdb;
    $wpdb->query(
        "DELETE FROM $wpdb->posts 
        WHERE post_type = 'revision' 
        AND post_parent > 0"
    );
}

Plugin Solutions

If you prefer using plugins, here are reliable options:

  1. Revision Control - Simple interface to manage revision settings
  2. Better Delete Revision - Cleanup and control revisions
  3. WP-Optimize - Includes revision management along with other optimization features

Additional Notes

  • Place custom code in functions.php or create a site-specific plugin
  • Test thoroughly after implementation
  • Back up your database before cleaning existing revisions
  • Consider server resources when setting revision limits

For most sites, keeping 5-10 revisions per post is sufficient for content management while maintaining good database performance.