我们要在woocommerce商店以及所有页面中隐藏/排除一些特定的woocommerce类别。
到目前为止,我们设法使用我在互联网上找到的代码来实现这一目标。 下面的代码会在商店页面中隐藏正确的类别,但是当我们使用woocommerve搜索进行搜索时,该类别不会隐藏在结果页面中。
//Insert excluded category ids here
$excludes = array(3380,3308);
$includes = explode(",",$widget_args['include']);
$includes = array_filter($includes, function($value) use ($excludes) {
return !in_array($value, $excludes);
});
$widget_args["include"] = implode(",", $includes);
return $widget_args;
}
add_filter( 'woocommerce_product_categories_widget_dropdown_args', 'exclude_woocommerce_widget_product_categories');
add_filter( 'woocommerce_product_categories_widget_args', 'exclude_woocommerce_widget_product_categories');
下面的代码确实在搜索页面中隐藏了类别,但在商店页面中却没有隐藏
add_filter( 'woocommerce_product_categories_widget_dropdown_args', 'organicweb_exclude_widget_category');
add_filter( 'woocommerce_product_categories_widget_args', 'organicweb_exclude_widget_category' );
function organicweb_exclude_widget_category( $args ) {
$args['exclude'] = array('15', '3380', '3308' ); // Enter the id of the category you want to exclude in place of '30'
return $args;
}
有人可以帮助我将两段代码合并在一起吗?
谢谢。
答案 0 :(得分:0)
您发布的两个代码段均仅从窗口小部件中隐藏类别,否则对隐藏类别无效。不是您目标的100%,对我来说可能有两件事:
如果要使用以下代码Exclude products from a particular category on the shop page进行操作(如果您选择在后端的“设计”>“定制程序”>“ WooCommerce”>“产品目录”下显示它们,则不会隐藏类别),如WooCommerce文档中所示。
/**
* Exclude products from a particular category on the shop page
*/
function custom_pre_get_posts_query( $q ) {
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'clothing' ), // Don't display products in the clothing category on the shop page.
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
add_action( 'woocommerce_product_query', 'custom_pre_get_posts_query' );
要实际上隐藏类别本身,请按照此处Hide a WooCommerce Category from Shop Page中的说明执行以下操作,该操作不会隐藏该类别的产品。
/**
* Show products only of selected category.
*/
function get_subcategory_terms( $terms, $taxonomies, $args ) {
$new_terms = array();
$hide_category = array( 126 ); // Ids of the category you don't want to display on the shop page
// if a product category and on the shop page
if ( in_array( 'product_cat', $taxonomies ) && !is_admin() && is_shop() ) {
foreach ( $terms as $key => $term ) {
if ( ! in_array( $term->term_id, $hide_category ) ) {
$new_terms[] = $term;
}
}
$terms = $new_terms;
}
return $terms;
}
add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );