I’ve been working on trying to hide all other categories from the category widget when a particular category is selected.
So, as an example, the site has 5x Products categories and and 1x Services category. When browsing the Services I do not want anything from the 5x products categories to display in the categories widget. The below code works fine to hide the 5x product categories but it hides it site wide, which I don’t want.
add_filter( 'woocommerce_product_categories_widget_args', 'exclude_widget_category' );
function exclude_widget_category( $args ) {
$exclude_terms = array();
array_push( $exclude_terms, 2548, 2245, 2775, 2913, 2846 );
$termchildren = get_term_children( '2548, 2245, 2775, 2913, 2846', 'product_cat' );
foreach( $termchildren as $child ) {
$term = get_term_by( 'id', $child, 'product_cat' );
array_push( $exclude_terms, $term->term_id );
}
$args['exclude'] = $exclude_terms;
return $args;
}
So to target the Services cat I added is_product_category and this works OK when on the services category but if i’m in a products category it completely breaks the page (no products appear, no categories etc). It also results in all subcategories in Services behaving like that too.
if ( is_product_category(2921) ) {
(2921 is my services category and 2548, 2245, 2775, 2913, 2846 are my product categories)
Also, I may as well add this now; need this to work the other way as well, so if you are in any of the products categories then the services categories should be hidden.
What am I doing wrong?
Many thanks.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Went about it a different way, works OK.
Just in case anyone else is looking for similar functionality;
//* dropdown
add_filter( 'woocommerce_product_categories_widget_dropdown_args', 'woo_product_cat_widget_args' );
//* list
add_filter( 'woocommerce_product_categories_widget_args', 'woo_product_cat_widget_args' );
function woo_product_cat_widget_args( $cat_args ) {
if ( is_product_category( 'experiences' ) || term_is_ancestor_of( 2921, get_queried_object_id(), 'product_cat' ) ) {
$cat_args['exclude'] = array(2548, 2245, 2775, 2913, 2846);
return $cat_args;
}
else {
$cat_args['exclude'] = array('2921');
return $cat_args;
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0