Exclude Woocommerce category with specific field value

I need to exclude certain categories ONLY from the Woocommerce shop page loop. Not the products, but only the categories. While I can still display these categories on the frontpage and such.

With the ‘get_terms’ filter I managed to remove a category statically, but the problem is that I need to read out those terms first for specific values to then exclude them. Which now creates a loop.

I’m not sure if there is a better filter, hook or something that alters the query so I can exclude showing these categories.

The code below is a fake example of what would crash the pages, but shows somewhat my intentions:

function woocommerce_exc_list_terms( $terms, $taxonomies, $args ) {

$query = array (
‘taxonomy’ => ‘product_cat’
);
$categories = get_terms($query);

$categories_to_exclude = array();

foreach ( $categories as $category ) {
if ( $category->some_meta_field >= ‘some_value’ ) { // for demonstration purposes
$categories_to_exclude[] = $category->slug;
}
}

$new_terms = array();

if(is_array($categories_to_exclude) && in_array( ‘product_cat’, $taxonomies ) && !is_admin() ) {

foreach ( $terms as $key => $term ) {

if ( ! in_array( $term->slug, $categories_to_exclude ) ) {
$new_terms[] = $term;
}

}

$terms = $new_terms;

}

return $terms;

}
add_filter( ‘get_terms’, ‘woocommerce_exc_list_terms’, 10, 3 );

Hopefully I explained my intentions clear enough!

Read more here:: Exclude Woocommerce category with specific field value

Leave a Reply

Your email address will not be published. Required fields are marked *