pagination count range of products on current page

2019-08-23 11:39发布

问题:

The pagination here works fine, but addition to pagination, as the limit per page is 3 suppose total 8 items in database so i want to display " showing 1 t0 3 item of 8" on page one, "showing 4 to 6 items of 8" on page two and so on. please help

$recordsLimit = 3;
$page = isset($_GET['page']) ? intval($_GET['page']): 1;
$totalProducts = countProducts($selectedCategoryId);
$totalPages = ceil($totalProducts / $recordsLimit);
$pageNumber = $recordsLimit * ($page - 1);
$products = getProductsByCatId($selectedCategoryId, $pageNumber, $recordsLimit);
        <?php if($totalProducts > $recordsLimit) : ?>
            <div class="pagination">
                <span>Page <?php echo $page.' of '.$totalPages; ?></span>
                <?php for($i=1; $i <= $totalPages; $i++) :
                        if($i == $page) { ?>
                            <strong><?php echo $i; ?></strong>
                 <?php  } else { ?>
                            <a href="products.php?cat_id=<?php echo $selectedCategoryId; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                 <?php  }
                     endfor; ?> 
    <?php endif; ?>

回答1:

Try:

echo "Showing ".( $page == 1 ? 1 : ($page -1) * $recordsLimit +1 )." to ".($page * $recordsLimit)." item of ".$totalProducts;


回答2:

Simply use this: <?php $firstNum = (($page-1)*$recordsLimit+1) ?> showing <?php echo $firstNum; ?> to <?php echo $firstNum+2;?> items of <?php echo $totalProducts;?>



回答3:

To fix the problem with Tom's code where the last page has an incorrect "to" number I added an offset variable. For this to work the $recordsLimit variable has to match the "showposts" argument in the query. The OP did not show his query so I'm showing the one I used.

$total_results = $wp_query->found_posts;

$recordsLimit = 10; 
$args['post_type'] = 'listings';
    $args['showposts'] = $recordsLimit;     
    $args['paged'] = $paged;
    $wp_query = new WP_Query($args);

$page = (get_query_var('paged')) ? get_query_var('paged') : 1;
$countoffset = ($page * $recordsLimit)-($total_results);
$countfrom = ( $page == 1 ? 1 : ($page -1) * $recordsLimit +1 );
$countto = ($page * $recordsLimit);
if(($total_results - $countfrom) < $recordsLimit) {$countto = ($countto - $countoffset);} 
echo 'Showing '.$countfrom.' to '.$countto.' of '.$total_results.' total results';