neilgee
neilgee

Reputation: 538

Get WooCommerce cart items count except for a product Category

I can get a WooCommerce cart content count with:

add_action('fl_body_open', 'cat_total_count');
function cat_total_count() {

echo WC()->cart->get_cart_contents_count();
}

How to reduce cart items total count for items that belong to a certain Product Category - 'box' for example?

Upvotes: 1

Views: 934

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254448

You can use Wordpress has_term() conditional function to exclude product category terms from a custom cart item count as follows:

add_action('fl_body_open', 'custom_total_cart_items_count');
function custom_total_cart_items_count() {
    // Below your category term ids, slugs or names to be excluded
    $excluded_terms = array('box'); 

    $items_count    = 0; // Initializing

    // Loop through cart items 
    foreach ( WC()->cart->get_cart() as $item ) {
        // Excluding some product category from the count
        if ( ! has_term( $excluded_terms, 'product_cat', $item['product_id'] ) ) {
            $items_count += $item['quantity'];
        }
    }
    echo $items_count;
}

Code goes in functions.php file of the active child theme (or active theme). It should works.

Note: To do the same thing for product tags replace 'product_cat' with 'product_tag'.

Upvotes: 2

Related Questions