0

I'm using this code to count the number of posts of a specific custom post type that have also a specific tag:

<?php 
    
    //Array
    $args = array(
        'post_type' => 'cars',
        'tag' => 'available'
    );
    $loop = new WP_Query( $args );
    if( $loop->have_posts() ) :
         $count_posts = wp_count_posts("cars")->publish;
?>

<?php
        echo "<p>Total:  $count_posts cars</p>";
    else:
?>   
<?php
    echo "<p>No cars available.</p>";
?>
<?php 
    endif;
    wp_reset_query();
?>

However the loop does not filter out the posts under "available" tag, but it just takes all the posts under "cars" post type.

Probably I'm close to the solution but I'm not getting what I'm doing wrong.

2
  • This has been answered here
    – Moishy
    Jan 12, 2023 at 17:39
  • wp_count_posts isn't using your query, it's independently counting how many instances of the "cars" post type there are.
    – vancoder
    Jan 12, 2023 at 23:11

1 Answer 1

1

wp_count_posts is not affect your custom query. You can use found_posts to return the number of posts from the custom query. So try to change the code after your loop query as follows. Hope it helps.

if ($loop->have_posts()) :
    $count_posts = $loop->found_posts;
    echo "<p>Total:  $count_posts cars</p>";
else :
    echo "<p>No cars available.</p>";
endif;
wp_reset_query();
1
  • Worked like a charm. Thanks a lot for your help! Jan 13, 2023 at 8:41

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.