Here is a function that allows you to check whether an item by product_id has already been added to the WooCommerce cart.
function woo_in_cart($product_id) { global $woocommerce; foreach($woocommerce->cart->get_cart() as $key => $val ) { $_product = $val['data']; if($product_id == $_product->id ) { return true; } } return false; } |
Usage :
if(woo_in_cart(123)) { // Product is already in cart } |
Here is an example that I had. I am programmatically inserting products to the cart but when the user decides to increase/decrease the quantity, I don’t want the cart to add the existing quantity.
$product_id = 123; // Example product_id $qty = 3; // Example qty $cart = WC()->instance()->cart; // Instantiate cart object /* * If the product exits in cart * just insert new quantity */ if(woo_in_cart($product_id)) { $cart_id = $cart->generate_cart_id($product_id); $cart_item_id = $cart->find_product_in_cart($cart_id); $cart->set_quantity($cart_item_id, $qty); } else { $cart->add_to_cart($product_id, $qty); } |
Hello!
Thank you for the snippet. it works great if to fix a small typo
function woo_in_cart() {
should be
function woo_in_cart($product_id) {
I needed it to add a class to the add to cart button if product in cart.
Thanks. $product_id has been added now.
You’re missing the $product_id in the function:
function woo_in_cart($product_id) {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val[‘data’];
echo “Product ID: “.$_product->id.””;
if($product_id == $_product->id ) {
return true;
}
}
return false;
}
Indeed! Thanks for spotting that. I’ve just updated the post.
Thanks for this. You’re missing a closing parenthesis, though, after (123):
if(woo_in_cart(123) {
// Product is already in cart
}
Cheers!
Thanks. Fixed!
Another way to do this:
function woo_is_product_in_cart( $product_id ) {
$cart_items = WC()->cart->get_cart();
$cart_item_data = wp_list_pluck( $cart_items, 'data' );
$cart_product_ids = wp_list_pluck( $cart_item_data, 'id' );
return in_array( $product_id, $cart_product_ids );
}
*thumb*
How can i restrict customer do not add any product if it is already available in cart ?
Are you asking to limit the amount of items a customer can add to their cart? So for example, they can only add 1 of product?
hello i tried to add you function to this code but didnt work , i need for redirect some products for some pages after user click to command thanks
add_action( ‘woocommerce_thankyou’, ‘bbloomer_redirectcustom’);
function bbloomer_redirectcustom( $order_id ){
global $current_user;
global $product;
$order = new WC_Order( $order_id );
$url =’192.168.2.26/wp-login.php’;
$url2=’www.kademia.tn’;
if (($order->status!=’failed’)&&($order->payment_method ==’other_payment’)&&((woo_in_cart($product_id))){
wp_redirect($url);
exit;
}
else if (($order->status!=’failed’)&&($order->payment_method ==’other_payment’)) {
wp_redirect($url2);
exit;
}
}