This is my first attempt at modifying the main query using the pre_get_posts
action/filter
This is the function currently hooked to it:
function advanced_product_search_filter($query)
{
if(!is_admin() &&
is_main_query() &&
is_search() && $query->query_vars['post_type'] == 'product')
{
$keyword = $_GET['s'];
if($_GET['exactly'])
$keyword = $_GET['s'] . ' "'. $_GET['exactly'] . '"';
if($_GET['without'])
{
$excluded = exclude_product_keyword_search($_GET['without'],
$_GET['pname'],
$_GET['pcode']
);
$query->set('post__not_in', $excluded);
}
if($_GET['pname'])
$query->set('s', $keyword);
else
$query->set('s', '');
if($_GET['pcode'])
{
$tax_queries = $query->get('tax_query');
$tax_queries[] = array(
array(
'taxonomy' => 'pa_ordering-code',
'field' => 'name',
'terms' => array($keyword),
'operator' => 'LIKE'
)
);
$query->set('tax_query', $tax_queries);
}
}
}
This is a plugin built on top of a WooCommerce
installation. So basically this function tries to support searching a WooCommerce
product either through the standard search (title and content) or an attribute search on a custom attribute called Ordering Code
which is pa_ordering-code
in the term_taxonomy
table
Other parts of the code works fine, I can modify the s
and post__not_in
vars without any problems, but if I try to use the tax_query
it, the query seems to break down.
To give you an idea, when I try this:
?s=foo&post_type=product&pname=1&pcode=1&without=non&exactly=foo+bar
dumping the WHERE
clause, I see this:
AND wp_posts.ID NOT IN (219)
AND 0 = 1
AND
(
(
(wp_posts.post_title LIKE '%foo%') OR
(wp_posts.post_content LIKE '%foo%')
) AND (
(wp_posts.post_title LIKE '%foo bar%') OR
(wp_posts.post_content LIKE '%foo bar%')
)
)
AND wp_posts.post_type="product"
AND (wp_posts.post_status="publish" OR wp_posts.post_status="private")
AND
(
(
wp_postmeta.meta_key = '_visibility' AND
CAST(wp_postmeta.meta_value AS CHAR) IN ('visible','search')
)
)
Notice the AND 0 = 1
? When I dump the JOIN
clause, I become sure that the tax_query
parameter isn’t being interpreted properly since I only see the postmeta
table in there. No terms
, term_relationships
, or term_taxonomy
table.
And I also tried simply overwriting the existing tax_query
(if there is one) by doing this:
$args = array(
array(
'taxonomy' => 'pa_ordering-code',
'field' => 'name',
'terms' => array($keyword),
'operator' => 'LIKE'
)
);
$query->set('tax_query', $args);
But I still could not get it to work. Any ideas as to what I may be doing wrong?