How to Limit Post Revisions in WordPress

Marek Z Dec 21, 2024 Post Revisions
How can I stop WordPress from saving so many versions of my posts?
What code snippet can I use to limit the number of post revisions in WordPress for better database performance?
Andy answered Dec 21, 2024

Method 1: Using wp-config.php Configuration

The simplest way to limit post revisions is by adding a constant definition to your wp-config.php file.

Add this line to limit revisions to a specific number (before the "/* That's all, stop editing! */" line):

define('WP_POST_REVISIONS', 5); // Change 5 to your desired number of revisions

To completely disable revisions, use:

define('WP_POST_REVISIONS', false);

Method 2: Using functions.php Filter

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

function limit_post_revisions($num, $post) {
    return 5; // Change 5 to your desired number of revisions
}
add_filter('wp_revisions_to_keep', 'limit_post_revisions', 10, 2);

Method 3: Clean Existing Revisions

Add this code to your theme's functions.php to remove old revisions:

function clean_old_post_revisions() {
    global $wpdb;
    $max_revisions = 5; // Change 5 to your desired number
    
    $post_ids = $wpdb->get_col("SELECT post_parent FROM {$wpdb->posts} WHERE post_type = 'revision' GROUP BY post_parent HAVING COUNT(*) > $max_revisions");
    
    if ($post_ids) {
        foreach ($post_ids as $post_id) {
            $revisions = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE post_type = 'revision' AND post_parent = $post_id ORDER BY post_modified DESC");
            $count = 0;
            foreach ($revisions as $revision) {
                $count++;
                if ($count > $max_revisions) {
                    wp_delete_post_revision($revision->ID);
                }
            }
        }
    }
}
add_action('init', 'clean_old_post_revisions');

Plugin Solutions

If you prefer using a plugin, here are reliable options:

  1. Revision Control - Gives you control over the number of revisions per post type
  2. WP Revisions Control - Simple interface to manage revision settings

Best Practices

  1. Start with Method 1 (wp-config.php) for site-wide settings
  2. Use Method 2 for more granular control
  3. Use Method 3 if you need to clean up existing revisions
  4. Consider using 5-10 revisions as a balanced number for most sites
  5. Monitor database size after implementing changes

Note: After implementing any of these methods, consider cleaning up your database using a tool like phpMyAdmin or a plugin like WP-Optimize to remove old revisions.