Pawan Kumawat

WooCommerce: Check if Product ID is in the Cart

To check if a specific product ID is in the cart in WooCommerce, you can use the `woocommerce_before_cart` action hook, which is fired before the cart page is displayed. Here’s how you can achieve this:

 

add_action('woocommerce_before_cart', 'check_product_id_in_cart');

function check_product_id_in_cart() {
    $product_id_to_check = 123; // Replace 123 with the ID of the product you want to check
    $product_in_cart = 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'];

        // Check if the product ID is in the cart
        if ($product_id === $product_id_to_check) {
            $product_in_cart = true;
            break;
        }
    }

    if ($product_in_cart) {
        // Product ID is in the cart, do something
        echo 'The product is in the cart.';
    } else {
        // Product ID is not in the cart, do something else
        echo 'The product is not in the cart.';
    }
}

 

Replace `123` with the ID of the product you want to check. This code will run when the cart page is loaded, and it will check if the specified product ID is in the cart. If the product ID is found in the cart, it will display “The product is in the cart.” If the product ID is not in the cart, it will display “The product 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

Top Quick View Plugins WooCommerce

There are several popular WooCommerce quick view plugins that provide a convenient way for customers to view product details without leaving the current page. Keep in mind that the popularity of plugins can change over time, so it’s a good idea to check for the latest information and reviews before making a decision.

Shortcodes included with Dokan

Dokan is a popular multi-vendor marketplace plugin for WooCommerce that allows you to create and manage a marketplace where multiple vendors can sell their products. Dokan provides several shortcodes that you can use to display various elements and functionalities on your marketplace pages. Here are some of the essential shortcodes provided by Dokan:

Upload Any File in My Account Registration Form

To allow users to upload a file in the My Account registration form in WooCommerce, you’ll need to customize the registration form and add a file upload field. We’ll use a custom function and a hook to achieve this. Here’s a step-by-step guide: