Print number of post (in reverse)

I’m trying to input the numer of the post next to it, but in the reverse order, which means

not

1
2
3
4

but

4
3
2
1
.

I have succeeded into doing it in the “right” order with this :

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<?php echo $wp_query->current_post + 1; ?>

but I can’t figure out how to do the opposite. Morethough, when I have my posts in several pages, it breaks aka

PAGE 1 : 1234
PAGE 2 : 1234 (should be 5678)

I have tried this :

<?php echo $wp_query->found_posts - $wp_query->current_post ?>

which inputs 8765
and then the next page 8765 instead of 4321…

3 Answers
3

To print a decreasing counter for the main home query, without sticky posts, you can try:

// current page number - paged is 0 on the home page, we use 1 instead
$_current_page  = is_paged() ?  get_query_var( 'paged', 1 ) : 1; 

// posts per page
$_ppp           = get_query_var( 'posts_per_page', get_option( 'posts_per_page' ) );

// current post index on the current page
$_current_post  = $wp_query->current_post;

// total number of found posts
$_total_posts   = $wp_query->found_posts;

// Decreasing counter    
echo $counter = $_total_posts - ( $_current_page - 1 ) * $_ppp - $_current_post;

Example:

For total of 10 posts, with 4 posts per page, the decreasing counter should be:

Page 1: 
    10 - ( 1 - 1 ) * 4 - 0 = 10
    10 - ( 1 - 1 ) * 4 - 1 = 9
    10 - ( 1 - 1 ) * 4 - 2 = 8
    10 - ( 1 - 1 ) * 4 - 3 = 7

Page 2: 
    10 - ( 2 - 1 ) * 4 - 0 = 6
    10 - ( 2 - 1 ) * 4 - 1 = 5
    10 - ( 2 - 1 ) * 4 - 2 = 4
    10 - ( 2 - 1 ) * 4 - 3 = 3

Page 3: 
    10 - ( 3 - 1 ) * 4 - 0 = 2
    10 - ( 3 - 1 ) * 4 - 1 = 1

or:

Page 1: 10,9,8,7
Page 2: 6,5,4,3
Page 3: 2,1

Update:

To support sticky posts we can adjust the above counter with:

// Decreasing counter    
echo $counter = $_total_posts
    + $sticky_offset 
    - ( $_current_page - 1 ) * $_ppp 
    - $_current_post;

where we define:

$sticky_offset =  is_home() && ! is_paged() && $_total_posts > $_ppp 
    ? $wp_query->post_count - $_ppp 
    : 0;

Note that there can be three cases of sticky posts:

  1. all sticky posts come from the first (home) page. (The number of displayed posts on the homepage is the same as without sticky posts).
  2. negative of 1)
  3. mixed 1) and 2)

Our adjustments should handle all three cases.

Leave a Comment