Detect Specific Product Categories in the WooCommerce Cart

Implementing conditional logic based on cart contents is a powerful way to enhance user interaction. By hooking into woocommerce_before_cart_contents, you can iterate through the WC()->cart object to check if any item belongs to a specific category using the has_term function. This technique is essential for displaying targeted notifications, applying category-specific shipping rules, or offering cross-sell promotions directly on the cart page based on the user's current selection.

Check Product Category in WooCommerce Cart with Code

Advanced Guides Code Snippets Coding Blog PHP Snippets Woocommerce WooCommerce Custom Code Woocommerce Hooks WooCommerce Tips Wordpress WordPress Code Snippets WordPress Development WP Hooks

Check Product Category in WooCommerce Cart with Code Tutorial/Guide

To determine whether a specific product category exists in the WooCommerce cart, use the woocommerce_before_cart_contents hook. This allows you to run a function just before cart items are rendered. Here's how you can set it up:

add_action('woocommerce_before_cart_contents', 'check_product_category_in_cart');

function check_product_category_in_cart() {
    $category_slug = 'your-category-slug'; // Enter the category slug you're targeting
    $category_found = false;

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

    foreach ($cart_items as $key => $item) {
        $product_id = $item['product_id'];

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

    if ($category_found) {
        echo 'The category is in the cart.';
    } else {
        echo 'The category is not in the cart.';
    }
}

Replace 'your-category-slug' with your actual category slug. You can insert this snippet into your active theme’s functions.php file or your custom plugin. It checks the cart contents and prints a message depending on whether the target category is present.

๐Ÿ’ก Have a Coding Problem?

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