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

时间:2020-07-08 14:02:43

标签: php wordpress woocommerce product cart

在WooCommerce中,我试图创建一个包含产品和结帐的一页着陆页。

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

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

我正在使用 Clear Woocommerce Cart on Page Load Even for logged in users 答案代码。

这就是我所拥有的:

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

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

1 个答案:

答案 0 :(得分:1)

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