wp_get_object_terms() to get a list of all the terms attached to all the posts in the current query

I think you’re on the right track because wp_get_object_terms() can take an array of IDs for its first argument, it’s just that $wp_query is not the array you want.

I can’t guarantee that this is more efficient (not my area of expertise), but I believe this [partially-tested] snippet would do what you want with at least one fewer loop and no array_unique():

// get $wp_query
global $wp_query;
// get array of post objects    
$my_posts = $wp_query -> posts;
// make array for the post IDs
$my_post_ids = array();
// loop through posts array for IDs
foreach( $my_posts as $my_post ) {
    $my_post_ids[] = $my_post->ID;
}
// get the terms
$my_terms = wp_get_object_terms( $my_post_ids, 'alfa' );

wp_get_object_terms() takes a 3rd $args parameter which you may need to set to get the ouput you want, but I’ll leave that to you.

UPDATE:
This can be even shorter using the new-to-me function wp_list_pluck(). Again this is untested but looks right:

// get $wp_query
global $wp_query;
// get array of post objects    
$my_posts = $wp_query -> posts;
// NEW: make array of the post IDs in one step
$my_post_ids = wp_list_pluck( $my_posts, 'ID' );
// get the terms
$my_terms = wp_get_object_terms( $my_post_ids, 'alfa' );

You can see in the source that this runs the same foreach loops code, but it looks a little nicer.

Leave a Comment