WooCommerce: Check if Product Category is in the Cart

To check if a specific product category is in the cart during the `woocommerce_before_cart` action hook, you can use a similar approach as in the previous answer. However, in this case, you need to use the `woocommerce_before_cart_contents` action hook, which fires before the cart items are displayed on the cart page. Here’s how you can achieve this:

 

add_action('woocommerce_before_cart_contents', 'check_product_category_in_cart');

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

    // Get the cart contents
    $cart_items = WC()->cart->get_cart();

    // Loop through the cart items
    foreach ($cart_items as $cart_item_key => $cart_item) {
        $product_id = $cart_item['product_id'];
        $product = wc_get_product($product_id);

        // Check if the product belongs to the desired category
        if (has_term($category_slug, 'product_cat', $product_id)) {
            $category_found = true;
            break;
        }
    }

    if ($category_found) {
        // Category is in the cart, do something
        echo 'The category is in the cart.';
    } else {
        // Category is not in the cart, do something else
        echo 'The category is not in the cart.';
    }
}

 

Replace `’your-category-slug’` with the desired category slug you want to check. This code will run when the cart page is loaded, and it will check if any product in the cart belongs to the specified category. If the category is found in the cart, it will display “The category is in the cart.” If the category is not in the cart, it will display “The category is not in the cart.”

Remember to place this code snippet in your theme’s `functions.php` file or in a custom plugin to ensure it runs properly on your WooCommerce store.

Categories

Related Blogs

Calculate distance between 2 address using latitude and longitude

To calculate the distance between two locations using their latitude and longitude coordinates, you can use the Haversine formula. The Haversine formula is commonly used to calculate the great-circle distance between two points on the surface of a sphere (such as the Earth) given their latitude and longitude.

WordPress Ajax login

To implement Ajax login in WordPress, you can follow these steps: 1. Open the theme’s functions.php file in your WordPress

Customize Woocommerce Settings Tab

Let’s talk about customizing Woocommerce Admin setting Tabs.To hide a specific Woocommerce setting tab or want to customize the Woocommerce setting tabs, not the entire sub-menu, but just a tab.For just Removing tabs we can use