3

I know I can get the terms for a single post using wp_get_post_terms, but is there a way (without writing a loop) to get all the terms in use by an array of posts?

1 Answer 1

4

That would be wp_get_object_terms. You'd need an array of post id's as the input, together with the taxonomy you want to retrieve the terms for (let's say: books). This should work (untested):

$my_query    = new wp_query ($args);
$my_posts    = $my_query->posts;
$my_post_ids = wp_list_pluck ($my_posts, 'ID');
$my_terms    = wp_get_object_terms ($my_post_ids, 'books');
2
  • 1
    I can confirm this works
    – Jules
    May 6, 2019 at 12:51
  • 1
    You can return only IDs in your query so that you don't need to use wp_list_pluck() php $taxonomy = '{my-taxonomy}'; $args = array( 'fields' => 'ids' ); $query = new WP_Query( $args ); $posts = $query->posts; $terms = wp_get_object_terms( $posts, $taxonomy ); developer.wordpress.org/reference/classes/wp_query/…
    – Pea
    Jun 7, 2019 at 20:25

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.