How to check if variable product id is in the woocommerce cart?

Member

by gilbert , in category: PHP CMS , 7 months ago

How to check if variable product id is in the woocommerce cart?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 7 months ago

@gilbert 

You can check if a variable product ID is in the WooCommerce cart by using the following PHP code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Get the current WooCommerce cart
$cart = WC()->cart->get_cart();

// Set the variable product ID you want to check
$product_id = 123; // Change this to the variable product ID you want to check

// Loop through each item in the cart
foreach ($cart as $cart_item_key => $cart_item) {
    // Get the product ID of the item in the cart
    $item_product_id = $cart_item['product_id'];

    // Check if the variable product ID is in the cart
    if ($item_product_id == $product_id) {
        echo 'Product is in cart';
        // You can perform any other actions here if the product is in the cart
        break; // Exit the loop once the product is found
    }
}


In this code snippet, replace 123 with the actual variable product ID you want to check. The code will loop through each item in the WooCommerce cart and check if the specified product ID is in the cart. If the product ID is found in the cart, you can perform any other actions within the loop.