如果产品不属于任何类别,Woocommerce 就会从搜索结果中删除产品

Sir*_*Haq 1 php wordpress woocommerce

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

我已经尝试过了,但这不起作用。

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'
   )));
  }
}
Run Code Online (Sandbox Code Playgroud)

Ava*_*yan 5

这对你有用:

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' ) )
            )
        ));
    }
}
Run Code Online (Sandbox Code Playgroud)

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