How to check for an array of product ids in woocommerce?

by mallory_cormier , in category: PHP CMS , a month ago

How to check for an array of product ids in woocommerce?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 3 days ago

@mallory_cormier 

In WooCommerce, you can check for an array of product ids using the is_product_in_cart() function. This function can be used to check if a specific product ID is in the current cart.


Here's an example of how you can check for an array of product ids in WooCommerce:

  1. Define an array of product ids that you want to check:
1
$product_ids = array(1, 2, 3, 4);


  1. Loop through the array of product ids and check if each product id is in the cart:
1
2
3
4
5
6
7
foreach ($product_ids as $product_id) {
    if (WC()->cart->is_product_in_cart($product_id)) {
        // Product is in the cart
    } else {
        // Product is not in the cart
    }
}


  1. You can also use the WC()->cart->get_cart() function to get an array of cart items and check if the product ids are in the cart:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$cart_items = WC()->cart->get_cart();

foreach ($cart_items as $item) {
    $product_id = $item['product_id'];
    
    if (in_array($product_id, $product_ids)) {
        // Product is in the cart
    } else {
        // Product is not in the cart
    }
}


By using these techniques, you can easily check for an array of product ids in WooCommerce and perform actions based on the results.