w206e

Add a post counter to each post that works with pagination

I needed to add an incrementing number to each post on an archive page within WordPress. The issue I was having was with pagination, the counter would be reset on each page.

To resolve this I had to get the posts per page and total posts and work out a formula for correctly setting my counter on each page.

<?php
$posts_per_page = get_option( 'posts_per_page' );
$total_posts = $GLOBALS['wp_query']->found_posts;
$total_pages = $posts_per_page / $total_posts;
$current_page = (get_query_var('paged')) ? get_query_var('paged') : 1;

if ( $current_page === 1 ) {
// On page 1 start at 1
$counter = 1;
} elseif ( $current_page === 2 ) {
// On page 2 start on the post per page + 1
$counter = $posts_per_page + 1;
} else {
// On other pages.
// For example on page 2 with 5 posts per page we want the counter to start on 6
// So page * posts per page - posts on the last page + 1 to get to this page = 6
$counter = ( $current_page * $posts_per_page - $posts_per_page + 1 );
} ?>

Thanks to the doc4design.com article for pointing me in the right direction.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s