Reputation: 478
I am trying to hide a product category from my product category menu.
add_filter( 'woocommerce_product_categories_widget_args', __NAMESPACE__ . '\\rv_exclude_wc_widget_categories' );
function rv_exclude_wc_widget_categories( $cat_args ) {
$cat_args['exclude'] = array('129'); // Insert the product category IDs you wish to exclude
$includes = explode(',', $cat_args['include']);
$cat_args['include'] = array_diff($includes,$cat_args['exclude']);
return $cat_args;
}
function exclude_category( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'cat', '-1, -129' );
}
}
add_action( 'pre_get_posts', 'exclude_category' );
The top function of my code successfully hides the category from my menu when actually in a category. However, it does not hide it from the main shop page. This is what I'm attempting with the bottom code, however, this doesn't appear to do anything.
Any ideas on how this can be done? The code is placed in my functions.php file.
EDIT: Trying to clarify what I'm asking.
When first opening my product page I now have the category 'TEST' hidden from my menu like below.
However, when I click into a product or category the menu goes back to displaying like below.
Upvotes: 1
Views: 3041
Reputation: 253773
For your first function (hiding a specific product category from widget):
add_filter( 'woocommerce_product_categories_widget_args', 'exclude_product_categories_widget', 10, 1 );
function exclude_product_categories_widget( $list_args ) {
$categories = array('129');
if(isset( $list_args['include'])):
$included_ids = explode( ',', $list_args['include'] );
$included_ids = array_unique( $included_ids );
$included_ids = array_diff ( $included_ids, $categories );
$list_args['include'] = implode( ',', $included_ids);
else:
$list_args['exclude'] = $categories;
endif;
return $list_args;
}
To exclude your products under product category (term ID) 129
in shop and archive pages use the following dedicated Woocommerce hooked function:
add_filter('woocommerce_product_query_tax_query', 'exclude_product_category_in_tax_query', 10, 2 );
function exclude_product_category_in_tax_query( $tax_query, $query ) {
if( is_admin() ) return $tax_query;
// HERE Define your product categories Terms IDs to be excluded
$terms = array( 129 ); // Term IDs
// The taxonomy for Product Categories custom taxonomy
$taxonomy = 'product_cat';
$tax_query[] = array(
'taxonomy' => $taxonomy,
'field' => 'term_id', // Or 'slug' or 'name'
'terms' => $terms,
'operator' => 'NOT IN', // Excluded
'include_children' => true // (default is true)
);
return $tax_query;
}
Code goes in function.php file of your active child theme (or theme). Tested and works.
Upvotes: 4