WooCommerce-从价格范围查询中隐藏产品类别

时间:2018-11-27 10:40:13

标签: php wordpress woocommerce

我当前正在使用默认的WooCommerce窗口小部件功能来按价格范围查询产品,其网址格式为www.mydomain.com/shop/?min_price=50&max_price=100

我现在正尝试从该查询中排除特定类别-将子弹设为hidden-category

我尝试使用以下代码,但是问题在于,当我转到以下代码时,它还会删除所有结果:

www.mydomain.com/category/hidden-category/

function custom_pre_get_posts_query( $q ) {
    $tax_query = (array) $q->get( 'tax_query' );
    $tax_query[] = array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'hidden-category' ),
           'operator' => 'NOT IN'
    );
    $q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' ); 

1 个答案:

答案 0 :(得分:0)

这就是我最终要去的事情:

第一个功能从搜索结果中隐藏hidden-category中的所有内容,第二个功能从价格范围查询中将其隐藏。

//hide sold from search results
function sm_pre_get_posts( $query ) {
   if (  $query->is_search() ) {
       $query->set( 'post_type', array( 'product' ) );
       $tax_query = array(
           array(
               'taxonomy' => 'product_cat',
               'field'   => 'slug',
               'terms'   => 'hidden-category', //slug name of category
               'operator' => 'NOT IN',
           ),
       );
       $query->set( 'tax_query', $tax_query );
    }
}
add_action( 'pre_get_posts', 'sm_pre_get_posts' );

//hide from query
function custom_pre_get_posts_query( $q ) {
if (!$q->is_main_query() || !is_shop() ) return;
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( 'hidden-category' ),
       'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );