How to use global post counter in the loop?

As I already stated in a comment,

You need to use get_option( 'posts_per_page' ) and get_query_var( 'paged' ) to calculate your post numbers

You can do something like the following: (I have commented the code to make it easy to follow. This goes into functions.php)

function get_post_number()
{
    global $wp_query;

    /*
     * Get current page number. Set page 1 to one as get_query_var( 'paged' ) will be 0
     */
    $current_page_number   = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
    /* 
     * Get the posts_per_page option that is set under "Reading"
     */
    $posts_per_page        = get_option( 'posts_per_page' );
    /*
     * Get the current post position in the loop, add 1 because the counter starts at 0
     */
    $current_post_position = $wp_query->current_post + 1;

    /*
     * If this is page one, return the post position as is
     */
    if ( $current_page_number == 1 )
        return $current_post_position;

    /*
     * Calculate the post number on paged pages
     */
    return ( $posts_per_page * ( $current_page_number - 1 ) ) + $current_post_position;
}

You can then use it as follow in your templates to display the correct post numbers (You need to use this inside the loop)

echo get_post_number();

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)