I excluded some products from woocommerce_product_query with this code:

  function en_archive_products_by_rol( $query ) {
    if (is_admin()) { 
    $meta_query = (array)$query->get('meta_query');
    $meta_query = array_merge( $meta_query,wpf_do_hide_product());
    $query->set( 'meta_query', array_unique($meta_query) );
    return $query;
add_action( 'woocommerce_product_query', 'en_archive_products_by_rol', PHP_INT_MAX  );

It works fine, but I'm trying to hide empty product categories on filter widget and it keeps counting excluded products in each category. I'm using this code:

function exclude_empty_terms_widget( $terms, $taxonomies, $args, $term_query ) {
    $new_terms = array();
    if ( ! empty( $terms ) && in_array( 'product_cat', $taxonomies ) ) {
        foreach ( $terms as $key => $term ) {
            if ( $term->count > 0 ) {
                $new_terms[] = $term;
        $terms = $new_terms;
    return $terms;
add_filter( 'get_terms', 'exclude_empty_terms_widget', PHP_INT_MAX, 4 );

Any ideas of what is wrong?

  • doing this will be very slow and expensive, the term counts are not the number of posts in that term with the current query, they're the number of posts on the site with that term regardless of the current query. You would need to calculate the number of posts in each term again for each term with your filter applied. On a large site this could take several minutes in a worst case scenario. This is on top of what looks like a worst case scenario meta query clause ( you never exclude things from queries, it gets very slow, you include instead. You should use a show option, not hide! )
    – Tom J Nowell
    Commented Feb 9, 2023 at 17:12
  • also note that WooCommerce and other 3rd party plugin questions are offtopic here and not in this stacks scope
    – Tom J Nowell
    Commented Feb 9, 2023 at 17:13


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.