skip to Main Content

I am using the following code:

/* Woocommerce - Add Product Count View in Each Category */
add_action( 'woocommerce_before_shop_loop', 'add_product_count_view', 20);

function add_product_count_view() {
    $terms = get_the_terms( $post->ID, 'product_cat');
    foreach( $terms as $term ) {
    if(is_tax('product_cat', $term->name)) {
        echo '<span class="count-view">'.$term->count
            .__( ' items')
            .'</span>';
        }
    }
} 

This code shows the total items in the store of the categories.

If a category has 20 items, 15 active and 5 inactive, it shows that there are 20 items in that category.

What I need is that it only shows the number of active articles in that category.

How can I fix it?

2

Answers


  1. You can get the count of products published on the product category page visited via the WC_Product_Query class (using the wc_get_products function):

    // shows the number of products published on the product category page
    add_action( 'woocommerce_before_shop_loop', 'add_product_count_view', 20);
    function add_product_count_view() {
    
        // only on the product category page
        if ( ! is_product_category() ) {
            return;
        }
    
        // gets the slug of the current product category
        $category_slug = get_queried_object()->slug;
    
        // gets the number of products published in the current category
        $args = array(
            'status'   => 'publish',
            'category' => array( $category_slug ),
            'return'   => 'ids',
            'limit'    => -1,
        );
        $products = wc_get_products( $args );
    
        echo '<span class="count-view">' . count($products) . __( ' items', 'woocommerce' ) . '</span>';
    
    }
    

    The code has been tested and works. Add it to your active theme’s functions.php.

    Login or Signup to reply.
  2. Easy solution is wc_get_loop_prop( 'total' ), which is returns total products of any WooCommerce archive pages.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search