Skip to content
Advertisement

Number of Posts – Display number (x of x), if number is less than 4 ( 4 is the post_per_page)

I am showing 4 custom post type posts per category on a parent post type archive page with category rows. I want to show the count of the category posts ($list->found_posts), but I am limiting the displayed posts to a random 4 posts.

<?php $list = new WP_Query (array(
 'posts_per_page' => 4,
 'post_type' => 'business_listing',
 'category__in' => 5,
 'orderby' => 'rand'
 )) ;

I have successfully displayed the total number of posts for each category (business_listing is the post type)

$listCat = get_category('5');
$catName = get_field('display_name', $listCat);
$numberPosts = wp_count_posts($list);
echo '<h3 class="directory text-left">'. get_cat_name($category_id = '5') .' ('. $list->found_posts .' of '. $list->found_posts .') <a href="'. get_category_link($listCat) .'">View All</a></h3>';

enter image description here

The issue is, that some of my queries have less than the 4 posts_per_page. So I wanted to count UP TO 4, so if the value is less than 4 posts it will only count that number. For example if there are 2 posts, it will say 2 of 2. But if there are 30 posts, it would say 4 of 30.

I hope this makes sense. Thanks for your help.

Advertisement

Answer

Try using the ternary operator:

echo '<h3 class="directory text-left">'. get_cat_name($category_id = '5') .' ('. ($list->found_posts < 4 ? $list->found_posts : 4)  .' of '. $list->found_posts .') <a href="'. get_category_link($listCat) .'">View All</a></h3>';
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement