What you do is query all the terms of a given taxonomy, and use them to query posts having them, so you're creating a WP_Query object for every single brand tax, which is unnecessarily expensive. What youYou should do instead isit the other way around; simply query posts which have terms of the brand taxonomy associated to it (and whichever additional feature you may want to use for the query) ONCE only, and while retrieving these posts (inside your wp_query loop), access the id of the currently queried post in the loop, and retrieve the brand
terms associated to it. Sth like this:
$product_query_args = array(
'post_type' => 'your_post_type',
'tax_query' => array(
array(
'taxonomy' => 'brand'
)
)
);
$product_request$products_request = new WP_Query( $product_query_args );
if ( $products_request->have_posts() ) {
while ( $products_request->have_posts() ) {
$products_request->the_post();
// Get ID of currently iterated post
$id_of_iterated_product = get_the_ID();
// Retrieve associated brand terms
$brands = get_the_terms( $id_of_iterated_product, 'brand' );
// Check if there are brand terms associated to iterated post
if ( ! empty( $brands ) ) {
// If so, iterate through them and get the name of each
foreach( $brands as $brand_key => $brand_object ) {
$brand_name = $brand_object->name;
// Do whatever you want with it
}
}
}
}
Like this, you actually only make one full query instead of twocountless, so performance should be better, hopefully. Let me know how this solution suits you.
To explain it a little further to you why I thought of hierarchical taxonomiestaxonomies; you wrote:
- From this I understand that there's somethinksomething like a category filter on your website, and you wanna display all the posts of that category, and then echo out the brands for each of these posts. For this, what you could actually do is simply query posts in function of the selected category (makes your query a lot easier), and then for each post retrieve and spit out the associated brands (which are all child tax's of the queried category, if you defined them to be so). You can however reach the same in querying your products in function of the given category, and then retrieve all the brand tags associated to each retrieved post as I did in my code; maybe that's even better when it comes to performance. But from a logical point of view, using taxonomy hierarchics and one single category query appears to be the easiest and most logical way of doing this.