Why WordPress Post IDs Are Not Sequential
It is normal for WordPress post IDs to appear non-sequential. This is not an error with your blog but the default behavior of WordPress, and it can usually be ignored.
However, for those with perfectionist tendencies or mild OCD, this can be quite bothersome.
How to Fix Non-Sequential Post IDs
WordPress does not provide a direct option in the admin panel to disable this behavior. To resolve the issue of non-sequential IDs, you can add code to clean up database records like drafts and revisions, and reset the auto-increment ID. The following method explains how to achieve this.
Implementation Steps
Navigate to your current theme directory, locate the functions.php file, and add the following code at the end of the file.
// WordPress: Fix Non-Sequential Post IDs
function keep_id_continuous() {
global $wpdb;
// Get the highest ID from published posts, drafts, private posts, and attachments
$lastID = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' OR post_status = 'draft' OR post_status = 'private' OR ( post_status = 'inherit' AND post_type = 'attachment' ) ORDER BY ID DESC LIMIT 1");
// Delete all auto-drafts and revisions with IDs greater than $lastID
$wpdb->query("DELETE FROM $wpdb->posts WHERE ( post_status = 'auto-draft' OR ( post_status = 'inherit' AND post_type = 'revision' ) ) AND ID > $lastID");
$lastID++;
// Reset the posts table auto-increment starting value
$wpdb->query("ALTER TABLE $wpdb->posts AUTO_INCREMENT = $lastID");
}
// Trigger cleanup when accessing New Post, New Media, or Menus pages
add_filter( 'load-post-new.php', 'keep_id_continuous' );
add_filter( 'load-media-new.php', 'keep_id_continuous' );
add_filter( 'load-nav-menus.php', 'keep_id_continuous' );
// Disable auto-save (remember to save manually when editing long posts)
add_action( 'admin_print_scripts', function() {
wp_deregister_script('autosave');
} );
// Disable post revisions
remove_action( 'pre_post_update', 'wp_save_post_revision' );
Code Explanation and Important Notes
- Functionality: This code automatically cleans up auto-drafts and revisions in the database when you access the "New Post," "New Media," or "Menus" pages. It resets the post table's auto-increment ID to the next value after the current highest valid ID, ensuring new posts receive sequential IDs.
- Critical Warning: The code disables WordPress's auto-save and revision features. When editing long posts, you must remember to save manually, or you may lose unsaved changes.
- Recommendation: Back up your website database before adding this code. This method is primarily for users who are bothered by non-sequential IDs and can accept the loss of auto-save and revisions. Sites with high content safety requirements should be cautious about disabling revisions.