页面加载时清空购物车允许在 WooCommerce 中添加到购物车

Empty cart upon page load allowing add to cart in WooCommerce

在 WooCommerce 中,我正在尝试创建包含产品和结帐的单页登录页面。

页面加载后,我希望清空购物车。 但我希望能够添加到购物车,并在同一页面结帐。

我只想在具有特定页面模板的页面上实现此目的。

我正在使用 答案代码。

这是我的:

?>
<?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' );
?>

我认为问题是页面在添加到购物车后刷新,因此再次清空购物车。我如何让它 运行 只有一次?还是有更好的方法来清理购物车?

更新 2

您可以在模板中尝试以下代码:

$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]" );