Php 如果产品不属于任何类别,Woocommerce将从搜索结果中删除这些产品
我正在尝试从搜索结果中删除那些不属于任何类别的产品 我试过这个,但不起作用Php 如果产品不属于任何类别,Woocommerce将从搜索结果中删除这些产品,php,wordpress,woocommerce,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(
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' ) )
)
));
}
}
在这种情况下,函数将返回未分配给任何帖子的术语ID排除术语数组,因为参数
'hide_empty'
默认为true
这将适用于您:
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' ) )
)
));
}
}
在本例中,函数将返回未分配给任何帖子的术语ID排除术语数组,因为参数
'hide_empty'
默认为true
谢谢您的回答,现在我得到了这个错误=>对象(WP#error){[“errors”=>数组(1){[“invalid_taxonomy”]=>数组(1){[0]=>字符串(16)“无效分类”}[“error_data”]=>array(0){}}是的,我的wordpress版本是4.6.1Sorry,我无法重现错误,这是我的工作。不适用于woocommerce 3+@Remi更新了答案,适用于当前wordpress/woocommerce安装。谢谢你的回答,现在我得到这个错误=>object(WP#u error){333(2){”错误“]=>array(1){[“invalid_taxonomy”]=>array(1){[0]=>string(16)“invalid taxonomy”}[“error_data”]=>array(0){}}是的,我的wordpress版本是4.6.1,我无法重现错误,我无法继续工作。不适用于woocommerce 3+@Remi更新了答案,适用于当前的wordpress/woocommerce安装。