Skip to content
Advertisement

Counting cart-items of specific product category

I am trying to get the number of items in the cart just from a specific product category in WooCommerce.

I am doing a site for a winery. It has alcoholic and non-alcoholic products. All the wine falls under the main category of ‘wine’ or category id 34, with many subcategories and products underneath them.

For any thing that falls under this category… I need to know how many items are in the cart under this category. If there are six bottles of wine no matter if they are all the same product id’s or 6 different product id’s. I need to get that number of 6 from the category of ‘wine’ or category id of 34.

I tried this with no success.

I am very new to WooCommerce and a little new to Object Oriented.

Thanks

function cat_cart_count( $cat_name ) {

// $cat_name variable is for you normally "tshirts" or "shorts"

global $woocommerce; $cat_count = 0; 

// For each product in the cart
foreach(WC()->cart->get_cart() as $cart_item_key => $values) { 
    $_product_id = $values['product_id']; // product ID
    $_product_qty = $values['quantity']; // product quantity

    // Getting categories of the product (could be more than one)
    $terms = get_the_terms( $_product_id, 'product_cat' );

    // Checking this product has a category
    if ( $terms && ! is_wp_error( $terms ) ) { 
        $term_name = array();

        // For each category of that product
        foreach($terms as $term) {

            // Adding the category name to an array
            $term_name[] = $term->name;

            // if the product has $cat_name category
            if ( in_array( $cat_name, $term_name ) ) {

                // add 1 x product quantity to the count
                $cat_count =+ 1 * $_product_qty;
            }
        }
    }
}

Advertisement

Answer

The WordPress conditional function has_term() accepts category ID, slug, name or an array of that values.

So that is the shorter and easy way to do it. Your code will be much more compact and lighter. And you can use directly your category ID 34.

Here is your function:

function cat_cart_count( $cat_name ) {
    $cat_count = 0; 
    
    // Iterating through each cart item
    foreach(WC()->cart->get_cart() as $cart_item)  
        if( has_term( $cat_name, 'product_cat', $cart_item['product_id']))
            $cat_count += $cart_item['quantity'];
            
    return  $cat_count;
}

This code is tested and fully functional.

Usage of your function using for example echo to display the value for 34 category ID:

echo cat_cart_count( 34 );
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement