Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

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

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?

Example:

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;
   }

   var_dump($draught_links);

    // do something
endwhile;

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?

share|improve this question
    
Are you trying to output how many posts are in a category in a loop or in single posts? –  Wyck May 23 '12 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. –  Wordpressor May 23 '12 at 9:53

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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