Pawan Kumawat

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.

WooCommerce: Display Regular & Sale Price @ Cart Table

Learn how to enhance your WooCommerce cart table by displaying both the regular and sale prices. Implement this functionality using WordPress hooks and filters to provide clear and appealing pricing information to your customers, encouraging sales and improving the shopping experience.

Jquery Form Validator

JQuery Form Validator is a featured jQuery plugin that makes it easy to validate user input while keeping your HTML clean from javascript code.