我有大约20000种产品,我正在使用electro主题。它们都属于未分类类别(id:979),大多数也属于其他类别。我想从搜索结果中隐藏那些只属于未分类的。我还想在产品页面中隐藏未分类的类别。
我使用了此代码,它从商店页面隐藏了未分类的类别,但产品仍显示在搜索结果中:
function wc_hide_selected_terms( $terms, $taxonomies, $args ) {
$new_terms = array();
if ( in_array( \'product_cat\', $taxonomies ) && !is_admin() && is_shop() ) {
foreach ( $terms as $key => $term ) {
if ( ! in_array( $term->slug, array( \'uncategorized\' ) ) ) {
$new_terms[] = $term;
}
}
$terms = $new_terms;
}
return $terms;
}
add_filter( \'get_terms\', \'wc_hide_selected_terms\', 10, 3 );
这些都是试图在搜索结果中隐藏未分类(仅限)的产品,但运气不佳:
function my_electro_search_categories_filter_args($args) {
$args[\'exclude\'] = \'uncategorized\';
return $args;
}
add_filter(\'electro_search_categories_filter_args\', \'my_electro_search_categories_filter_args\');
function sp_pre_get_posts( $query ) {
if ( !is_admin() && $query->is_main_query()) {
$query->set( \'cat\', \'-979\' );
}
}
add_action( \'pre_get_posts\', \'sp_pre_get_posts\' );
UPDATE
我用下面的答案修复了它,如下所示(但我不知道它在性能方面是否合适):
function custom_pre_get_posts_query( $q ) {
$tax_query = (array) $q->get( \'tax_query\' );
$tax_query[] = array(
\'taxonomy\' => \'product_cat\',
\'field\' => \'slug\',
\'terms\' => array( \'axesouar-kinitis\', \'gnisia-axesouar\', \'axesouar-tablet-hy\', \'tilefonia\', \'statheri-tilefonia\', \'lipa-prionta\', \'exoplismos-service-norton\', \'antallaktika\' ),
\'operator\' => \'IN\'
//\'terms\' => array( \'uncategorized\' ),
//\'operator\' => \'NOT IN\'
);
$q->set( \'tax_query\', $tax_query );
}
add_action( \'woocommerce_product_query\', \'custom_pre_get_posts_query\' );