Created
December 12, 2019 07:14
-
-
Save kartikparmar/903c06ec9f62c619f160308ede5fb5a2 to your computer and use it in GitHub Desktop.
Hide WooCommerce Category and its sub-categories from Shop page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 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 | |
// Getting ids of sub-categories start | |
$child_args = array( | |
'taxonomy' => 'product_cat', | |
'hide_empty' => false, | |
'parent' => 126 | |
); | |
$child_product_cats = get_terms( $child_args ); | |
foreach( $child_product_cats as $sub_category ) { | |
array_push( $hide_category, $sub_category->term_id ); | |
} | |
// Getting id of sub-categories ends | |
// 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 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment