WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a custom post type and a custom taxonomy located in a plugin. In writing my output loop for the CPT, I'm trying to output all the custom tax items assigned to the CPT items at the top of the page before outputting each individual CPT item.

This is what I'm hoping to achieve:

tax 1 | tax 2 | tax 3 | tax 4 ...


I assume wp_get_object_terms() is the best way to get at the tax items, but I have to pass in the $post->ID or, in my case, an array of ID's as a parameter.

Is there a way to write only 1 loop which would grab the IDs, do its thing and them move on to output the CPT items, or do I have to write 2 loops, 1 which first builds the array of CPT post ID's to pass into the function and then a 2nd which outputs the CPT items? Am I missing something else entirely?

Thanks for your help!

share|improve this question
up vote 1 down vote accepted

Yes there is a way using only one loop but that can be messy and have on resources for large amounts of data,

To do that you simple store all of the output as a variable and only output after you finished your loop, ex:

$tax_array = array();
$output = '';
while ( have_posts()) {
    $output .=  '<div class="item">';
    $output .=  '<div class="item_title">'.get_the_title().'</div>';
    $output .=  '<div class="item_content">'.get_the_content().'</div>';
    $output .=  '</div>';

    $temp = wp_get_object_terms($post->ID,'tax_name');
    $tax_array = array_merge($tax_array,(array)$temp);

so after this single loop you have all of the items output in $output and $tax_array holds an array of all terms that you need.

share|improve this answer
Excellent. Thanks – JohnG Apr 23 '12 at 12:57

Your Answer


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.