phpwordpresswoocommercecartproduct

WooCommerce if condition (if product is in cart do something)


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>';
 }
}

Solution

  • 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 */