【问题标题】:Empty cart upon page load allowing add to cart in WooCommerce页面加载时的空购物车允许在 WooCommerce 中添加到购物车
【发布时间】:2020-10-28 23:17:38
【问题描述】:

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

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

【问题讨论】:

  • 是的,已启用
  • 我还没有找到限制自定义模板页面的方法……
  • 代码会直接在模板中工作吗?
  • 更新了我的答案……你可以试试或者用我的新答案……我希望它会起作用。

标签: php wordpress woocommerce product cart


【解决方案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]" );

【讨论】:

  • 太棒了 - 但由于 functions.php 是通用的,我需要将“// 仅保留添加到购物车的最后一项”以特定页面模板为条件。这可能吗?
  • @tiny Update 2 ...我找到了另一种可行的方法...尝试并告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-29
  • 1970-01-01
  • 2013-09-16
  • 2018-08-26
  • 2020-06-06
  • 2021-07-26
  • 2015-10-10
相关资源
最近更新 更多