Woocommerce从搜索结果中删除不属于任何类别的产品


Woocommerce remove products from search result if they are not in any category

我试图从搜索结果中删除不属于任何类别的产品。

我已经试过了,但是行不通。

add_action('pre_get_posts', 'products_pre_get_posts');
function products_pre_get_posts($query) {
  if ( ! is_admin() && is_search() && is_shop() ) {
    $query->set( 'tax_query', array(array(
       'taxonomy' => 'product_cat',
       'field' => 'slug',
       'terms' => array( '' ),
       'operator' => 'NOT IN'
   )));
  }
}

这将为您工作:

add_action( 'pre_get_posts', 'products_pre_get_posts' );
function products_pre_get_posts( $query ) {
    if ( ! is_admin() && $query->is_main_query() && $query->is_search() ) {
        $query->set( 'tax_query', array(
            array(
                'taxonomy'  => 'product_cat',
                'field'     => 'term_id',
                'terms'     => get_terms( array( 'taxonomy' => 'product_cat', 'fields' => 'ids' ) )
            )
        ));
    }
}

在这种情况下,函数get_terms()将返回一个不包括未分配给任何帖子的术语id的数组,因为参数'hide_empty'默认为true