Display post number not post ID number

Post ID’s aren’t meant to be sequential. To number your posts sequentially, you’d have to use a meta field. There was discussion of this while back on this question:

Change Permalinks Structure to a Sequential Number for Each Post?

And the best answer for what you’re looking to do seemed to be a snippet of code posted on the support forums:

http://wordpress.org/support/topic/display-sequential-post-numbercount-not-post-id

function updateNumbers() {
    /* numbering the published posts, starting with 1 for oldest;
    / creates and updates custom field 'incr_number';
    / to show in post (within the loop) use <?php echo get_post_meta($post->ID,'incr_number',true); ?>
    / alchymyth 2010 */
    global $wpdb;
    $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts 
                 WHERE $wpdb->posts.post_status="publish" 
                 AND $wpdb->posts.post_type="post" 
                 ORDER BY $wpdb->posts.post_date ASC";
    $pageposts = $wpdb->get_results($querystr, OBJECT);
    $counts = 0 ;
    if ($pageposts):
    foreach ($pageposts as $post):
        $counts++;
        add_post_meta($post->ID, 'incr_number', $counts, true);
        update_post_meta($post->ID, 'incr_number', $counts);
    endforeach;
endif;
}  

add_action ( 'publish_post', 'updateNumbers', 11 );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

(I modified it very slightly to sort by post date, rather than just ID as the initial code did.)

It will hook into all post actions (save/publish/delete) and update the ‘incr_number’ custom field for all posts. So you’ll have a performance lag on saving posts when you have a large number in the database, but once the posts are saved, showing the number is as simple as

echo get_post_meta( $post->ID, 'incr_number', true );

Leave a Comment

error code: 523