Discussion:
Get terms from wp_query when using tax_query
Filippo Pisano
2014-02-12 16:22:50 UTC
Permalink
Hi all,

I was wondering if there is a smart/quick way to obtain all terms attached
to a post when querying posts through WP_Query();


This is the scenario:

$query = array(
"post_type" => "post",
"tax_query" => array(
array(
"taxonomy" => "my_tax",
"fields" => "slug",
"terms" => "my-term"
)
)

);
$posts = new WP_Query($query);

It would of great hand if it could also return all terms attached to a post

foreach($posts as $post){
var_dump( $post->terms['my_tax'] ); // could store all terms grouped by
taxonomy
}

The only way to obtain the same result, as I know, is to loop through each
post and query for terms attached to it:

foreach($posts as $post){
$post->terms['my_tax'] = wp_get_object_terms($post, 'my_tax'); // very
expensive
}


What do you think? Is there a way to modify posts structure returned by
wp_query without writing custom sql queries?




Filippo Pisano
Jeremy Clarke
2014-02-17 14:55:24 UTC
Permalink
On Wed, Feb 12, 2014 at 11:22 AM, Filippo Pisano
Post by Filippo Pisano
I was wondering if there is a smart/quick way to obtain all terms attached
to a post when querying posts through WP_Query();
The terms for all posts in a query should be fetched while WP_Query is
going through it's various motions. They are saved to the object cache so
you won't find them in each $post, but once a post has been queried you can
fetch it's terms for free (no db queries, fast access to object cache).

I think that answers your question. Yes, you'll have to loop through all
taxonomies you are interested in to act on them, but it shouldn't be any
harder than looping through a $post->terms array, and avoids cluttering up
WP_Query objects with tons of metadata.
--
Jeremy Clarke • jeremyclarke.org
Code and Design • globalvoicesonline.org
Continue reading on narkive:
Loading...