I used this in a loop on a category template to get a numbered lists of posts that continues in the next page:
<?php
$mypage = (get_query_var('paged')) ? get_query_var('paged') : 1;
$ppp = get_query_var('posts_per_page');
$counter = ($mypage * $ppp) - $ppp;
while(have_posts()) : the_post(); $counter++; ?>
<div class="entry">
<?php echo $counter; the_title(''); ?>
</div>
<?php endwhile; ?>
It was suggested by s-ha-dum as an answer to another question on StackExchange.
However, I need this loop to sort posts in asc order, and I am not sure how to do that with all these variables in place. Normally, I would use something like the following before the loop and it would work perfectly:
<?php $sortorder= new WP_Query( 'orderby=date&sort=asc' ); ?>
The end result of the code is this:
<?php
$mypage = (get_query_var('paged')) ? get_query_var('paged') : 1;
$ppp = get_query_var('posts_per_page');
$counter = ($mypage * $ppp) - $ppp;
$sortorder= new WP_Query( 'orderby=date&sort=asc' );
while ( $sortorder->have_posts() ) : $sortorder->the_post(); $counter++ ?>
<div class="entry">
<?php echo $counter; the_title(''); ?>
</div>
<?php endwhile; ?>
But this is not working as expected. It does sort them in ascending order, but all pages show the same list of titles, with only the number changing. So the same 10 titles are shown in page one, numbered 1-10, then again in page 2, but numbered from 11... and so on.
So please excuse my ignorance and help me understand where I am going wrong and how to fix it.
Thank you.
Update: This is the final working query:
<?php
$mypage = (get_query_var('paged')) ? get_query_var('paged') : 1;
$ppp = get_query_var('posts_per_page');
$counter = ($mypage * $ppp) - $ppp;
$query = new WP_Query( array(
'category_name' => 'research',
'paged' => $paged,
'posts_per_page' => 20,
'orderby' => 'date',
'order' => 'asc',
) );
while ( $query->have_posts() ) : $query->the_post(); $counter++ ?>
<div class="entry">
<?php echo $counter; the_title(''); ?>
</div>
<?php endwhile; ?>
Update #2: Improved answer based on further comments by Jaydip Nimavat.
The loop in the category page template is now:
<?php
$mypage = (get_query_var('paged')) ? get_query_var('paged') : 1;
$ppp = get_query_var('posts_per_page');
$counter = ($mypage * $ppp) - $ppp;
while ( have_posts() ) : the_post(); $counter++ ?>
<div class="entry">
<?php echo $counter; the_title(''); ?>
</div>
<?php endwhile; ?>
And the functions.php
now includes:
// Sort order for research, articles, and literature category pages
function custom_posts_per_page($query) {
if( !is_admin() && $query->is_category( array('research','articles','literature') )) {
$qobj = get_queried_object();
if( isset($qobj->taxonomy) && 'category' == $qobj->taxonomy ) {
$query->set( 'orderby', 'date' );
$query->set( 'order', 'asc' );
}
}
}
add_filter( 'pre_get_posts', 'custom_posts_per_page' );
And everything works perfectly. Thank you, Jaydip.