【问题标题】:Unable to clear WooComerce cart when navigating to a new page inside Wordpress [duplicate]导航到 Wordpress 中的新页面时无法清除 WooCommerce 购物车 [重复]
【发布时间】:2020-11-18 18:39:12
【问题描述】:

每当访问者导航到特定页面(ID #1)时,我都会尝试清空 Woocomerce 购物车。

环境:

WP 5.4.2

Woocomerce 4.2.2

Woodmart 主题

Litespeed 缓存(已禁用)and applied these recommendations

使用谷歌浏览器/火狐浏览器测试。隐身模式和普通模式。

on this similar question 的答案都没有帮助

我在functions.php中使用这个代码:

add_action( 'template_redirect', 'woocommerce_clear_cart' );
function woocommerce_clear_cart() {
  global $woocommerce, $post;
    if( $post->ID == 1) {
      WC()->cart->empty_cart();
      WC()->session->set('cart', array());
    }
}

结果:

  1. 客户进入产品页面并将产品添加到购物车。(我的模板显示了迷你购物车中的产品)
  2. 客户导航到页面 id 1。
  3. 产品仍显示在迷你购物车中/或导航到购物车页面时。
  4. 购物车只有在使用 CTRL+F5 重新加载浏览器后才会清空,没有缓存。或在页面之间导航几次之后。

见解:

  • 预期结果正确发生当我以管理员身份登录时(导航到第 1 页时购物车清空)
  • 清空客户会话(WooCommerce/Status/Tools -> 清除客户会话)后用户添加产品(在步骤 1 和 2 之间)导航到页面 id 1 会产生预期的结果。
  • 我怀疑是浏览器缓存问题。
  • 当页面#1 加载时打印出WC()->session 时,我可以看到步骤 1 中的购物车项目。

是否有一些 WC 方法可以以编程方式从数据库中清除特定的客户会话?

我也试过这段代码,但这些都没有给我预期的结果

add_action( 'template_redirect', 'woocommerce_clear_cart' );
function woocommerce_clear_cart() {
    if( $post->ID == 1) {
        WC()->session->set( 'cart', null );
        WC()->session->set( 'cart_totals', null );

        $cart = WC()->cart; 
        foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {

                $cart->remove_cart_item( $cart_item_key ); // remove it from cart
        } 
    }
}

【问题讨论】:

    标签: php wordpress session woocommerce


    【解决方案1】:

    试试:

    add_action( 'init', 'woocommerce_clear_cart_url' );
    function woocommerce_clear_cart_url() {
      global $woocommerce;
    
        if ( is_front_page() && isset( $_GET['empty-cart'] ) ) { 
            WC()->cart->empty_cart(); 
        }
    }
    

    这是首页,替换为您选择的页面。

    【讨论】:

    • 如您所见,我正在使用此代码。它不适合我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    相关资源
    最近更新 更多