WooCommerce Cart: Check if a Product from a Category Exists

Hooks Woocommerce WooCommerce Customization WooCommerce Development Woocommerce Hooks WooCommerce Tips Wordpress WordPress Development WordPress Hacks

WooCommerce Cart: Check if a Product from a Category Exists Tutorial/Guide

In WooCommerce, you may want to perform custom actions when a product from a particular category is in the cart. This can be done by hooking into the woocommerce_before_cart_contents action, enabling you to personalize the cart experience based on the category.  

Step-by-Step Guide to Check Product Category

The following code snippet shows how to check if a product from a specific category is in the cart:

add_action('woocommerce_before_cart_contents', 'check_product_category_in_cart');

function check_product_category_in_cart() {
    $category_slug = 'your-category-slug'; // Replace with your category's slug
    $category_found = false;

    $cart_items = WC()->cart->get_cart();

    foreach ($cart_items as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);

        if (has_term($category_slug, 'product_cat', $product_id)) {
            $category_found = true;
            break;
        }
    }

    if ($category_found) {
        echo 'The product category is in your cart!';
    } else {
        echo 'No items from this category in your cart.';
    }
}

Explanation of the Code

This function checks every product in the cart and sees if it belongs to the specified category. If a match is found, it displays a message indicating the presence of the product category in the cart.

Enhancements for Your Store

  • Offer a special discount for products in the selected category.
  • Provide a free gift or a promo code when a product from the category is added.
  • Modify shipping options based on the presence of certain categories in the cart.

Adding the Code to Your Site

Insert the code in the functions.php file of your theme, or for a more modular approach, create a custom plugin.

Related Links

💡 Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.