I am trying to search for a product by attribute as taxonomy but the query doesn't return any result. In my example I hard coded id 58 which has attached 3 products to it. My attribute is called Make and I am using pa_make.
function custom_search($q)
{
if ($q->is_search()) {
$tax_query = array(
array(
'taxonomy' => 'pa_make',
'field' => 'id',
'terms' => [58],
'operator' => 'IN'
)
);
$q->set("tax_query", $tax_query);
}
}
add_action("woocommerce_product_query", "custom_search");
EDIT:
<form action="/" id="search-form" class="filters-wrapper">
<input type="hidden" name="s" value="" />
<input type="hidden" name="post_type" value="product" />
<input type="checkbox" name="search_make" value="58" checked />
</form>
The form is submitted on checkbox click via JS. Don't know how does will help but still.
EDIT 2:
function custom_search($q)
{
$tax_query = (array)$q->get('tax_query');
if ($q->is_search()) {
$tax_query = array(
'taxonomy' => 'pa_make',
'field' => 'id',
'terms' => [58],
'operator' => 'IN'
);
$q->set("tax_query", $tax_query);
}
}
echo "<pre>";
var_dump($tax_query);die;
add_action("woocommerce_product_query", "custom_search");
This way by adding my tax_query to the previous array the var dump shows:
array(3) {
["relation"]=>
string(3) "AND"
[0]=>
array(4) {
["taxonomy"]=>
string(18) "product_visibility"
["field"]=>
string(16) "term_taxonomy_id"
["terms"]=>
array(1) {
[0]=>
int(9)
}
["operator"]=>
string(6) "NOT IN"
}
[1]=>
array(4) {
["taxonomy"]=>
string(11) "pa_make"
["field"]=>
string(2) "id"
["terms"]=>
array(1) {
[0]=>
int(58)
}
["operator"]=>
string(2) "IN"
}
}
fieldshouldn't beterm_id? - Sergiu Paraschivpa_makehas two values with IDs58,60. Not sure what more I have to provide. I`ll put the form that calls the search. - Toma Tomov$q->is_search()istrue,pa_makeis the correct taxonomy name,inis the correct field name,woocommerce_product_queryis not intercepted by something else before or is manipulated after your action, your action is actually added at all (because maybe it's not added at the right time), etc. In other words the syntax looks correct, that is indeed the way you add atax_queryto awoocommerce_product_query, but other than that there's not much more one can see here. - Sergiu Paraschiv