Display post number not post ID number

I am wanting to display the number order of a post. I tried using<?php the_ID(); ?> but this just displays the post ID and doesn’t seem to do go in sequential order due to post revisions and whatnot.

Is there a way to to display if the post is #2 or #3 or #4 and so on?

Read More

Thanks!

Related posts

Leave a Reply

2 comments

  1. 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 );
    
  2. If you don’t want to save the sequential post number in custom field and update it on every post action you can get all posts as an array of wordpress IDs and then search this array to get the single post number.
    I use get_posts to retrieve all IDs and I order posts ascending by date, so the oldest of all posts will always be first in the array:

        $postId = get_the_ID();
    
        $allPosts = get_posts(array(
            'fields' => 'ids',
            'numberposts' => -1,
            'orderby' => 'date',
            'order' => 'ASC'
        ));
    
        $postNumber = array_search($postId, $allPosts) + 1;
        echo $postNumber;