I have a shortcode that shows a loop for a custom post type:

while ( $loop->have_posts() ) : $loop->the_post();  
   // do something

Some of the posts are in categories ($term->name), how do I display list of these categories and posts within them based on that loop?


I have 2 categories - "Foo" and "Bar", I have 5 posts in "Foo" and 5 posts in "Bar".

I'm displaying all the posts and get something like this below them:

Foo (5) | Bar (5)

But in different loop I'm using posts_per_page() limiter, and I'm displaying only 3 posts, not 10, so I want to get:

Foo (3)

I was trying something like this:

while ( $loop->have_posts() ) : $loop->the_post(); 

   $terms = get_the_terms($post->ID, 'portfolio_categories');  

   foreach ( $terms as $term ) {
      $draught_links[] = $term->name;


    // do something

But doing foreach inside of while loop is messy and I'm getting something like

Foo (1) Foo (2) Foo (3) Foo (4) Foo (5) Foo (5) Bar (1) Foo (5) Bar (2) ...

Any ideas?

  • Are you trying to output how many posts are in a category in a loop or in single posts?
    – Wyck
    Commented May 23, 2012 at 5:50
  • Each post is only in one category (or not) so I'm trying to display how many posts are in certain category in a loop. The problem is foreach doesn't work like expected within while loop. Commented May 23, 2012 at 9:53

1 Answer 1


I think you can try the following options.

wp_list_categories with the 'show_count' parameter http://codex.wordpress.org/Template_Tags/wp_list_categories

get category and use $count = $category->category_count; http://codex.wordpress.org/Function_Reference/get_category

You can traverse up the functions to get_term if those don't work and see what is in there, even though you probably can use get the terms you will have to parse the array for output as can be seen in your example, so the above 2 methods would most likely be better.

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.