0

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!

1 Answer 1

1

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.

0

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.