页面加载时清空购物车,允许在WooCommerce中添加到购物车 [英] Empty cart upon page load allowing add to cart in WooCommerce

查看:73
本文介绍了页面加载时清空购物车,允许在WooCommerce中添加到购物车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.

这就是我所拥有的:

?>
<?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?

推荐答案

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

这篇关于页面加载时清空购物车,允许在WooCommerce中添加到购物车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆