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 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 ...

CPT 1
CPT 2
CPT 3
...

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

1 Answer 1

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()) {
    the_post();
    $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

 
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.