I put a number before the post title in Wordpress and number ordering is desc.
This code in my theme's index.php:
<div id="content">
<?php if ( have_posts() ) : $post_nr = $wp_query->post_count; ?>
<?php while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php echo $post_nr--;?>. Book Title: <span class="title"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>. Writer: <?php the_tags(' '); ?>. Publisher: <?php the_category(', '); ?>. </span>
</div>
<?php endwhile; ?>
<?php endif;?>
</div>
My problem, it's code does not function if I use page navigation. If I click page2, page3, ..., it's numbering don't show real total post.
Any help me, please. What code should I add and placed where?
For this to work properly, we need:
The current post position
Total amount of posts
Amount of posts per page
The current page we are on
Lets look at a possible function to achieve this
function get_post_position_in_reverse()
{
// Invoke the global $wp_query object
global $wp_query;
// Make sure that we are actually inside the loop, if not, bail
if ( !in_the_loop() )
return false;
//Setup our variables we will be using
// Get the current page we are on
if ( get_query_var( 'paged' ) ) {
$current_page = get_query_var( 'paged' );
} elseif ( get_query_var( 'page' ) ) {
$current_page = get_query_var( 'page' );
} else {
$current_page = 1;
}
// Get the current post's position plus 1 as post counter starts at 0
$post_position = $wp_query->current_post + 1;
// Get the total amount of posts in the query
$total_posts = $wp_query->found_posts;
// Get the amount of posts_per_page from backend
$ppp = get_option( 'posts_per_page' );
/**
* Now that we have everything set up, we need to do the maths
*
* If we have 20 posts across 4 pages with 6 posts per page, we will have
* 6 posts on pages 1,2 and 3 and only 2 posts on page 4. Our post numbers
* will be as follow, the first post on page one will be 20 and the last
* post on page 4 will be 1
*/
$number = $total_posts - ( ( $current_page * $ppp ) - ( $ppp - $post_position ) ) + 1;
return number_format_i18n( $number );
}
You can now add it anywhere inside the loop as follow
echo get_post_position_in_reverse();
Try function instead of query
$post_nr = wp_count_posts();