Reputation: 342
Im trying to display additional button [Book Your appointment] on the WooCommerce Cart page that would take user to a page with a product for booking an appointment. This part works nicely. I also try to check if product ID 444908 is already in cart. Product ID 444908 is an appointment product, and if a person has already booked an appointment the button should not be displayed as the person already have booked product in the cart. Seems like the problem is with my IF condition. When I'm using it it doesn't show button no matter if product 444908 is or isn't in cart.
What am I doing wrong?
add_action( 'woocommerce_after_cart_totals', 'my_continue_shopping_button' );
function my_continue_shopping_button() {
$product_id = 444908;
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
if ( $in_cart ) {
echo '<div class="bookbtn"><br/>';
echo ' <a href="/book-appointment/" class="button"><i class="fas fa-calendar-alt"></i> Book Your Appointment</a>';
echo '</div>';
}
}
Upvotes: 2
Views: 4247
Reputation: 32354
find_product_in_cart
returns a empty string if product is not found
so you need
if ( $in_cart !="" )
Upvotes: 0
Reputation: 1088
Here's something I've been using for a while now 🙃
function is_in_cart( $ids ) {
// Initialise
$found = false;
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
// For an array of product IDs
if( is_array($ids) && ( in_array( $cart_item['product_id'], $ids ) || in_array( $cart_item['variation_id'], $ids ) ) ){
$found = true;
break;
}
// For a unique product ID (integer or string value)
elseif( ! is_array($ids) && ( $ids == $cart_item['product_id'] || $ids == $cart_item['variation_id'] ) ){
$found = true;
break;
}
}
return $found;
}
For single product ID:
if(is_in_cart($product_id)) {
// do something
}
For array of product/variation IDs:
if(is_in_cart(array(123,456,789))) {
// do something
}
...or...
if(is_in_cart($product_ids)) {
// do something
}
Upvotes: 2
Reputation: 342
In the end I used external function:
function woo_is_in_cart($product_id) {
global $woocommerce;
foreach($woocommerce->cart->get_cart() as $key => $val ) {
$_product = $val['data'];
if($product_id == $_product->get_id() ) {
return true;
}
}
return false;
}
Then I check if the product is in cart using this:
if(woo_is_in_cart(5555) !=1) {
/* where 5555 is product ID */
Upvotes: 1