Reputation: 816
I am working on a small wordpress hobby project and I have run into a bit of a snag. I have implemented WooCommerce and am using Category and Tags for my data.
I have some entries which I know relate so for an example, the data would model as follows:
Car #1: Category => Sedan Tag => Volvo
Car #2: Category => Sedan Tag => Volvo
Car #3: Category => Sedan Tag => BMW
I am trying to filter these WooCommerce products to ensure that both tag and category match so in this instance, Car #1 is related to Car #2 and Car #3 is an Orphan.
The current query that is being generated when getting related products is as follows:
SELECT * FROM wp_posts p
INNER JOIN wp_postmeta pm ON ( pm.post_id = p.ID AND pm.meta_key='_visibility' )
INNER JOIN wp_term_relationships tr ON (p.ID = tr.object_id)
INNER JOIN wp_term_taxonomy tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id)
INNER JOIN wp_terms t ON (t.term_id = tt.term_id)
WHERE (( tt.taxonomy = 'product_cat' AND t.term_id IN ( 14 )))
OR (( tt.taxonomy = 'product_tag' AND t.term_id IN ( 44) ));
The query gives me the correct result when I use OR however with more data I then get results which only satisfy one criteria which doesn't work well. I think the issue is that it is only fetching one taxonomy row per post so when I use AND (in where conditions) instead of OR in the query above, it doesn't work.
Does anyone know of a solution to this or has experiencing a similiar issue? Alternatively is there a better way that I should structure the products?
Thanks!
Upvotes: 0
Views: 4425
Reputation: 629
Use WP_Query
with tax_query
and define an AND
relation there to get the correct query. For example in your case something like this might work;
$args = array(
'post_type' => 'product',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'volvo' ),
),
array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => array( 'sedan' ),
),
),
);
$query = new WP_Query( $args );
For more information see the WordPress Codex on WP_Query. Good luck!
Upvotes: 2