Search code examples
phpwordpresswoocommerceproductcart

Empty cart upon page load allowing add to cart in WooCommerce


In WooCommerce, I'm trying to create a one-page landing page with a product and checkout.

When the page is loaded I want the cart to empty. But I want to be able to add to cart, and checkout on the same page.

I want to achieve this only on pages with a specific page-template.

I'm working from Clear Woocommerce Cart on Page Load Even for logged in users answer code.

This is what I have:

?>
<?php 
//epmty cart
if (! WC()->cart->is_empty() ) {
    WC()->cart->empty_cart( true );
}
<?php 
// show add to cart button
echo do_shortcode( '[add_to_cart id='22']');
?>
// allow checkout Even though Cart Is Empty
add_filter( 'woocommerce_checkout_redirect_empty_cart', '__return_false' );
add_filter( 'woocommerce_checkout_update_order_review_expired', '__return_false' );
?>
<?php 
echo do_shortcode( '[woocommerce_checkout' );
?>

The problem I think is that the page refreshes upon add to cart and therefor empties the cart again. How do I make it run only once? or is there a better way to clear the cart?


Solution

  • Update 2

    You could try the following code in your template:

    $current_product_id = 22; // The product ID 
    $cart               = WC()->cart; // The WC_Cart Object
    
    // When cart is not empty 
    if ( ! $cart->is_empty() ) {
        // Loop through cart items
        foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
            // If the cart item is not the current defined product ID
            if( $current_product_id != $cart_item['product_id'] ) {
                $cart->remove_cart_item( $cart_item_key ); // remove it from cart
            }
        }
    } 
    // When cart is empty
    else {
        // allow checkout Event
        add_filter( 'woocommerce_checkout_redirect_empty_cart', '__return_false' );
        add_filter( 'woocommerce_checkout_update_order_review_expired', '__return_false' );
    }
    
    // show add to cart button
    echo do_shortcode( "[add_to_cart id='22']");
    
    // show Checkout
    echo do_shortcode( "[woocommerce_checkout]" );