0

I'm trying to achieve the following search result counts while using pagination;

Showing 1-9 of 368 Items - (Page One)

Showing 9-18 of 368 Items - (Page Two)

but I'm getting myself turned around with $count_posts; I'm not sure I'm fully grasping it. :/


PHP (Search.php)

<?php $post_count = $wp_query->post_count; ?>
<?php $count_products = wp_count_posts( 'products' )->publish; ?>
<?php $count_posts = wp_count_posts()->publish; ?>

HTML/PHP (Search.php)

<p class="small text-uppercase">Showing <?php echo $post_count; . '-' . $post_count; ?> of <strong><?php echo $count_products ?> items</strong></p>

My Question: How can I achieve the result I am after?

EDIT: 4 JUL 14:56

After quite a bit of testing I was able to figure it out with the help of, @KrzysiekDróżdż.

if ( !is_paged() ) {
    // first page of pagination
    $first_post = absint( $wp_query->get('paged') - 1 );
    $last_post = $first_post + $wp_query->post_count - 1;
    $all_posts = $wp_query->found_posts;
} else {
    $first_post = absint( $wp_query->get('paged') - 1 ) * $wp_query->get('posts_per_page') + 1;
    $last_post = $first_post + $wp_query->post_count - 1;
    $all_posts = $wp_query->found_posts;
} 

1 Answer 1

2

I'm afraid you're doing it a little bit wrong...

Here are the problems:

  1. post_count field contains the number of posts being displayed and not the offset.
  2. wp_count_posts returns the number of posts globally, not in current query (so it will not be true for queries that have some filters).
  3. echo $post_count; . '-' . $post_count; is not correct PHP code.

So how to do this?

All you need is the info from WP_Query:

<?php
    $first_post = absint( $wp_query->get('paged') - 1 ) * $wp_query->get('posts_per_page') + 1;
    $last_post = $first_post + $wp_query->post_count;
    $all_posts = $wp_query->found_posts;
?>
<p class="small text-uppercase">Showing <?php echo $first_post . '-' . $last_post; ?> of <strong><?php echo $all_posts; ?> items</strong></p>
8
  • 2
    I believe 'page' needs to be 'paged' in this case. Commented Jun 28, 2019 at 10:36
  • Interesting, so as I'm using <?php $the_query = new WP_Query( $args ); ?> Could I substitute $wp_query for $the_query? Also I believe there to be a syntax error in $first_post somewhere but I can't see it. :/
    – Lewis
    Commented Jun 28, 2019 at 11:47
  • 1
    @JacobPeattie yep, great catch :) Commented Jun 28, 2019 at 11:48
  • 1
    Found the syntax error @KrzysiekDróżdż. You're missing the closing bracket on absint.
    – Lewis
    Commented Jun 28, 2019 at 12:06
  • 1
    @Beaniie there was one redundant opening bracket - writing code on mobile is hard ;) Commented Jun 28, 2019 at 12:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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