Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I know how to keep track on the 'index' of the current post when running the loop using

$wp_query->current_post

Bu this restarts the count from zero on subsequent paged pages. So if I have 20 posts, and show 5 posts per page, then on page 2 the posts are again numbered 0-4 instead of 5-9.

My question is: Is there a build in way to get the absolute index when running the loop on a paged page, or do I have to calculate the offset myself, using information about page number and posts per page?

share|improve this question

2 Answers 2

$wp_query->current_post holds information about current post in loop, not global set of posts. Numering posts across multiple pages is not available natively (as far as I know) and probably would be to unreliable (for example what if number of posts per page changes is customized to be uneven?).

For specific implementation building custom numbering, based on page number is probably indeed only option.

As for stickies you can retrieve their count with something like count( get_option('sticky_posts') ) and adjust your numbering by that.

share|improve this answer

hopefully someone will provide a better answer, but for now I'm doing this:

// We're about top start The Loop.
// Setting up a counter to keep track of the posts being processed
// We can't just use current_post as it start from zero on subsequent paged pages.

$paged_no = ($wp_query->query_vars['paged'] < 2 ) ? 0 : $wp_query->query_vars['paged'] -1 ;
$current_offset = $paged_no * $wp_query->query_vars['posts_per_page'];

and then inside the loop:

$absolute_post_index = $wp_query->current_post+$current_offset+1;

This works when there are no sticky posts. If there are any, they will be stuck on the first page. This means that if there are 5 posts per page, and one sticky post, the first page will display 6 posts, and subsequent pages will display 5 posts. In that scenario page one will number the posts 0-5 and on page two the posts will be numbered 5-9, because the sticky post is no longer being considered. That's a problem because it means that the same index will be repeated for the last post on page 1 and the first post on page 2.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.