Reputation: 45
hello guys i'm trying to know if a specific category with some custom attributes has a product or not but i don't know how to use this function to check if it has or no
$isset_products_in_category = new WP_Query(
array(
'post_type' => 'product',
'posts_per_page' => -1,
'relation'=>'AND',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '5',
'operator' => 'IN',
),
array(
'taxonomy' => 'pa_color',
'field' => 'term_id',
'operator' => 'IN',
'terms' => '2',
),
),
'ignore_stickie_posts' => true,
'fields' => 'ids',
)
);
Upvotes: 0
Views: 412
Reputation: 7
There are two key issues in your WP_Query code
i) Incorrect Placement of relation
The 'relation' => 'AND' must be placed inside the 'tax_query' array, not at the top level.
2) Typos in Argument Keys
'ignore_stickie_posts' is a typo; it should be 'ignore_sticky_posts'. 'relation' must be moved under tax_query.
Corrected Codes below
$isset_products = new WP_Query(
array(
'post_type' => 'product',
'posts_per_page' => -1,
'ignore_sticky_posts' => true,
'fields' => 'ids',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => 5,
'operator' => 'IN',
),
array(
'taxonomy' => 'pa_color',
'field' => 'term_id',
'terms' => 2,
'operator' => 'IN',
),
),
));
And then check if the category has products or empty like below
if ($isset_products->have_posts()): { echo 'somthing'; } else{ echo 'Not found'; }
Don't forget to
wp_reset_postdata();
Upvotes: 0
Reputation: 486
'relation' => 'AND'
should be part of the tax_query
array in WP_Query()
(it defines the relationship between the arrays in the tax_query
).Revised code example:
<?php
$wp_query = new WP_Query(
array(
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
'relation'=>'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '5',
'operator' => 'IN',
),
array(
'taxonomy' => 'pa_color',
'field' => 'term_id',
'terms' => '2',
'operator' => 'IN',
),
),
'ignore_sticky_posts' => true,
'fields' => 'ids',
)
);
// Do something with the result of the query
$isset_products_in_category = $wp_query->post_count > 0;
var_dump($isset_products_in_category); // will output bool(true) or bool(false).
Upvotes: 0