【问题标题】:Problem on redirection on the "add to cart" button woocommerce to checkout关于“添加到购物车”按钮 woocommerce 到结帐的重定向问题
【发布时间】:2020-04-04 19:56:34
【问题描述】:

你好,我遇到了类似的问题

How to remove woocommerce added cart items and redirect to checkout?

在产品页面上当我点击添加到购物车时,我总是收到此错误“您无法在购物车 woocommerce 中添加另一个 [产品]”

我尝试了 LoicTheAztec 发布的解决方案

1) 加入购物车前清空购物车(如果购物车不为空)

add_filter( 'woocommerce_add_to_cart_validation', 'one_cart_item_at_the_time', 10, 3 );
function one_cart_item_at_the_time( $passed, $product_id, $quantity ) {
    if( ! WC()->cart->is_empty())
        WC()->cart->empty_cart();
    return $passed;
}

2) 添加到购物车重定向到结帐:

add_filter( 'woocommerce_add_to_cart_redirect', 'add_to_cart_checkout_redirection', 10, 1 );
function add_to_cart_checkout_redirection( $url ) {
    return wc_get_checkout_url();
}

3) 跳过购物车页面重定向到结帐:

add_action('template_redirect', 'skip_cart_page_redirection_to_checkout');
function skip_cart_page_redirection_to_checkout() {
    if( is_cart() )
        wp_redirect( wc_get_checkout_url() );
}

此解决方案有效并解决了我的问题,但第一个 sn-p 删除了我已经在购物篮中的所有其他产品,我应该只重置当前产品,而不是整个购物车。我该如何解决这个问题?

【问题讨论】:

    标签: wordpress woocommerce hook-woocommerce


    【解决方案1】:

    在第一个sn-p中试试这个代码,它会检查购物车是否有产品,如果找到则重定向here:

    add_filter('woocommerce_add_to_cart_validation', 'one_cart_item_at_the_time', 10, 3);
    
    function one_cart_item_at_the_time( $passed, $product_id, $quantity ) {
        if(! WC()->cart->is_empty()) {
            $cartId = WC()->cart->generate_cart_id($product_id);
            $cartItemKey = WC()->cart->find_product_in_cart($cartId);
            if ($cartItemKey) {
              return $passed;
            } else {
              $woocommerce->cart->add_to_cart( $product_id );
              return $passed;
            }
        }
    }
    

    【讨论】:

    • 我尝试在“$id = $product->get_id();”行上给我“致命错误:未捕获的错误:在 null 上调用成员函数 get_id()”
    • 我已经修改了代码,请替换后重试
    • 未捕获的错误:在同一行“$id=$product->get_id();”上的布尔值上调用成员函数 get_id()
    • 哦,我发现产品id已经包含在参数中了,我现在已经编辑了代码。请再试一次:) 抱歉!
    • 感谢您的帮助,我已经头疼了 2 天了。现在代码没有错误,但它只是消除了产品,当我为购物车中已有的产品单击“添加到购物车”时,它只是将其删除。我认为要使其正常工作,我必须取消产品并立即将其添加回购物车,所以我没有收到“您的产品已经在购物车中”的错误消息,但我该怎么做呢?非常感谢你帮助我
    猜你喜欢
    • 2013-03-13
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2014-09-10
    相关资源
    最近更新 更多