2

I have an array of ids that correspond to terms. How do I get the full term objects for each id?

$ids = array(1,2,3);

Ideally, I would love to be able to do something similar to the way taxonomy queries with WP_Query work, but obviously with terms instead of posts.

2
  • Could you not loop through the array and use get_term?
    – gdaniel
    Jul 29, 2014 at 20:46
  • I could, and I did do that as a crutch to get the script working. But if there is a single function that can handle all of this for me, it would make my code simpler and shorter and I would be relying on the WordPress API more appropriately... and I would learn something new.
    – Jeff
    Jul 30, 2014 at 16:13

2 Answers 2

5

I wonder if you mean something like this modified Codex example:

// Fetch:
$terms = get_terms( 'category', array(
    'include' => array( 1, 2, 3 ),
) );

// Output:
if ( ! empty( $terms ) && ! is_wp_error( $terms ) )
{
     $li = '';
     foreach ( $terms as $term )
     {
       $li .= sprintf( "<li>%s</li>", $term->name );    
     }
     printf( "<ul>%s</ul>", $li );
 }

where $terms contains an array of term objects, empty array or the WP_Error() object.

Check the Codex on get_terms() to get more information on the output and the input arguments. There you can get more code examples.

2
  • 2
    That looks exactly what I am looking for. I misunderstood what include was actually including.
    – Jeff
    Jul 30, 2014 at 16:10
  • @Jeff That's great - exclude should work in a similar way and if include is empty then every term is included. Just remember to use the correct taxonomy (category, post_tag, ... ) else you will get the WP_Error object.
    – birgire
    Jul 30, 2014 at 16:18
0

See http://codex.wordpress.org/Function_Reference/get_term_by

Create a foreach loop for your array.

foreach($ids as $id) {
    $terms[$id] = get_term_by('id', $id, 'category');
}

var_export($terms);

You can then do what you want with the data.

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.