我正在尝试改变WooCommerce商店的搜索功能,以便当用户进行匹配product_tag
slug返回未指定产品标签的产品。
这背后的逻辑是向搜索“面筋”的用户显示所有不含面筋的产品。
除了操作符参数外,我的代码几乎正常工作。
我正在抛出此查询:
http://example.com/?s=gluten
This function returns all the products tagged as the search query:
function menta_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by(\'slug\', get_query_var(\'s\'), \'product_tag\');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
\'taxonomy\' => \'product_tag\',
\'field\' => \'slug\',
\'terms\' => $term->slug,
\'operator\' => \'IN\'
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars[\'tax_query\'] = $query->tax_query->queries;
}
}}
add_action( \'pre_get_posts\', \'menta_pre_get_posts\', 1 );
But if I change the operator to NOT IN, I get no results:
function menta_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_search() && $query->is_main_query() ) {
$term = get_term_by(\'slug\', get_query_var(\'s\'), \'product_tag\');
if ( $term && !is_wp_error( $term ) ) {
$tax_query = array(
\'taxonomy\' => \'product_tag\',
\'field\' => \'slug\',
\'terms\' => $term->slug,
\'operator\' => \'NOT IN\'
);
$query->tax_query->queries[] = $tax_query;
$query->query_vars[\'tax_query\'] = $query->tax_query->queries;
}
}}
add_action( \'pre_get_posts\', \'menta_pre_get_posts\', 1 );
产品标签正确,有些产品没有面筋标签