Display product counter only in subcategories – WooCommerce

  php, woocommerce, wordpress

Hello stackoverflow community.

I am trying to get functionality to display a product counter but only in subcategories. In the main categories I want to disable it.

At the moment I have been able to do this:

function add_product_count_view()
{
    global $wp_query;

    $category_id = $wp_query->get_queried_object()->term_id;
    $query = new WP_Query(array(
  'tax_query' => array(
      array(
          'taxonomy' => 'product_cat',
          'field' => 'id',
          'terms' => $category_id,
          'include_children' => true,
      ),
  ),
  'nopaging' => true,
  'fields' => 'ids',
  ));

    if (function_exists("is_shop") && $category_id != 0) {
        echo '(' .esc_html($query->post_count) . ')';
    }
}

and output

<span class="custom-home-category-counts">
       <?php do_action('count_product_title');?>
</span>

This way I got what I want but the counter shows the same value for each subcategory
counter

Source: Ask PHP

LEAVE A COMMENT