'Hide multiple child-category from displaying on category page in woocommerce
I would like to hide multiple child-categories (CAT1, CAT2) from displaying on the main category page in woocommerce. I have found some code that works for this.
add_filter( 'get_terms', 'exclude_category', 10, 3 );
function exclude_category( $terms, $taxonomies, $args ) {
$new_terms = array();
if ( is_product_category() ){
foreach ( $terms as $key => $term ) {
if( is_object ( $term ) ) {
if ( 'CAT1' == $term->slug && $term->taxonomy = 'product_cat' ) {
unset($terms[$key]);
}
elseif ( 'CAT2' == $term->slug && $term->taxonomy = 'product_cat' ) {
unset($terms[$key]);
}
}
}
}
return $terms;
}
But the only way it works if I create a new "elseif" line for every category that i want to hide. Is there a way to chain these two together?
if ( 'CAT1' == $term->slug && $term->taxonomy = 'product_cat' ) {
unset($terms[$key]);
}
elseif ( 'CAT2' == $term->slug && $term->taxonomy = 'product_cat' ) {
unset($terms[$key]);
}
Solution 1:[1]
Yes, you can use in_array(), store terms you want to unset in $exclude_terms and pass that in in_array($term->slug, $exclude_terms). Here is the complete code:
add_filter( 'get_terms', 'exclude_category', 10, 3 );
function exclude_category( $terms, $taxonomies, $args ) {
$exclude_terms = array('CAT1', 'CAT2', 'CAT3');
if ( is_product_category() ){
foreach ( $terms as $key => $term ) {
if( is_object ( $term ) ) {
if ( in_array($term->slug, $exclude_terms) && $term->taxonomy = 'product_cat' ) {
unset($terms[$key]);
}
}
}
}
return $terms;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex McCain |
