【问题标题】:Empty cart button on woocommerce cart page does not work properlywoocommerce 购物车页面上的空购物车按钮无法正常工作
【发布时间】:2021-04-29 12:42:44
【问题描述】:

我正在使用此代码在我的 woocommerce 购物车页面(靠近更新购物车按钮)上创建一个按钮:

add_action( 'woocommerce_cart_actions', 'woocommerce_empty_cart_button' );
function woocommerce_empty_cart_button() {
    echo '<a href="' . esc_url( add_query_arg( 'empty_cart', 'yes' ) ) . '" class="button" title="' . esc_attr( 'Empty Cart', 'woocommerce' ) . '">' . esc_html( 'Empty cart', 'woocommerce' ) . '</a>';
    }
    
add_action( 'wp_loaded', 'woocommerce_empty_cart_action', 20 );
function woocommerce_empty_cart_action() {
    if ( isset( $_GET['empty_cart'] ) && 'yes' === esc_html( $_GET['empty_cart'] ) ) {
        WC()->cart->empty_cart();
    
        $referer  = wp_get_referer() ? esc_url( remove_query_arg( 'empty_cart' ) ) : wc_get_cart_url();
        wp_safe_redirect( $referer );
        }
    }

问题是它只能通过单击两次才能工作。 我认为问题可能是我正在使用此链接将产品添加到购物车:

/cart/?add-to-cart=25366

知道如何解决这个问题吗?

【问题讨论】:

    标签: php wordpress woocommerce cart


    【解决方案1】:

    问题出在一行:

    $referer  = wp_get_referer() ? esc_url( remove_query_arg( 'empty_cart' ) ) : wc_get_cart_url();
    

    wp_get_referer()函数返回当前页面的referer。基本上是带你到当前页面的链接。

    欲了解更多信息:https://developer.wordpress.org/reference/functions/wp_get_referer/

    如果您之前添加过产品,点击清空购物车按钮后,您将被重定向到将产品添加到购物车的链接。

    你可以这样解决:

    // adds the button to the cart page
    add_action( 'woocommerce_cart_actions', 'woocommerce_empty_cart_button' );
    function woocommerce_empty_cart_button() {
        echo '<a href="' . esc_url( add_query_arg( 'empty_cart', 'yes' ) ) . '" class="button" title="' . esc_attr( 'Empty Cart', 'woocommerce' ) . '">' . esc_html( 'Empty cart', 'woocommerce' ) . '</a>';
    }
    
    // empty the cart and refresh the page (redirects to the cart page)
    add_action( 'wp_loaded', 'woocommerce_empty_cart_action', 20 );
    function woocommerce_empty_cart_action() {
        if ( isset( $_GET['empty_cart'] ) && 'yes' === esc_html( $_GET['empty_cart'] ) ) {
            WC()->cart->empty_cart();
        
            $referer = wc_get_cart_url();
            wp_safe_redirect( $referer );
        }
    }
    

    代码已经过测试并且可以运行。将其添加到您的活动主题的 functions.php 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-06
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多