Create a Custom Function to Limit WordPress Post Revisions

Alex T. Dec 19, 2024 WordPress Performance
How can I make my WordPress only save a few versions of my posts instead of a lot?
What is the custom code snippet to limit the number of post revisions in WordPress to improve database performance?
Andy answered Dec 19, 2024

Solution to Limit WordPress Post Revisions

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 WordPress will keep for each post:

define('WP_POST_REVISIONS', 5);

For more control, this code allows you to set different revision limits for different post types:

function limit_post_revisions($num, $post) {
    switch ($post->post_type) {
        case 'post':
            return 5; // Keep 5 revisions for posts
        case 'page':
            return 3; // Keep 3 revisions for pages
        default:
            return 2; // Keep 2 revisions 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_action('init', 'disable_revisions_for_post_types');

WordPress Configuration File Method

Alternatively, you can add this line to your wp-config.php file (place it before the "/* That's all, stop editing! */" line):

define('WP_POST_REVISIONS', 5);

Plugin Solutions

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

  1. Revision Control

    • Set revision limits per post type
    • Delete old revisions
    • User-friendly interface
  2. Simple Revisions Delete

    • Basic revision management
    • One-click revision cleanup

Important Notes

  • After implementing any of these solutions, old revisions will remain in the database
  • To remove existing revisions, you'll need to clean them up manually or use a plugin
  • Choose a reasonable number of revisions (3-5 is usually sufficient)
  • Test the solution on a staging site first
  • Back up your database before making any changes