Wordpress Woocommerce 产品正在页面刷新时添加到购物车

问题描述 投票:0回答:3

我在使用 woocommerce 时遇到问题。

将产品添加到购物车后,浏览器中的链接变为 link/?add-to-cart=72,如果我刷新页面,产品会再次添加到购物车中。

每次刷新都会将产品添加到购物车中。 我禁用了除 woocommerce 之外的所有插件,但仍然一样。

关于如何解决这个问题有什么想法吗?谢谢。

php wordpress woocommerce
3个回答
16
投票

我曾经遇到过同样的问题,这是您应该添加到主题的

functions.php
文件或您自己的自定义插件中的代码:

add_action('add_to_cart_redirect', 'cipher_add_to_cart_redirect');
 
function cipher_add_to_cart_redirect($url = false) {
 
     // If another plugin beats us to the punch, let them have their way with the URL
     if(!empty($url)) { return $url; }
 
     // Redirect back to the original page, without the 'add-to-cart' parameter.
     // We add the `get_bloginfo` part so it saves a redirect on https:// sites.
     return get_bloginfo('wpurl').add_query_arg(array(), remove_query_arg('add-to-cart'));
 
}

当用户将产品添加到购物车时,它将添加重定向。我希望这有帮助。


1
投票

感谢@asfandyar-khan的回答,它对我有用。

不过有一点更新,自 3.0.0 版本起,add_to_cart_redirect 已被弃用,我们需要使用 woocommerce_add_to_cart_redirect 代替。

这使得:

add_action('woocommerce_add_to_cart_redirect', 'example_add_to_cart_redirect');

function example_add_to_cart_redirect($url = false) {
 
     // If another plugin beats us to the punch, let them have their way with the URL
     if(!empty($url)) { return $url; }
 
     // Redirect back to the original page, without the 'add-to-cart' parameter.
     // We add the `get_bloginfo` part so it saves a redirect on https:// sites.
     return get_bloginfo('wpurl').add_query_arg(array(), remove_query_arg('add-to-cart'));
 
}

0
投票
add_action('woocommerce_add_to_cart_redirect', 'cipher_add_to_cart_redirect');

function cipher_add_to_cart_redirect($url = false) {
    // If another plugin beats us to the punch, let them have their way with the URL
    if (!empty($url)) {
        return $url;
    }

    // Get the URL of the current product
    if (isset($_REQUEST['add-to-cart'])) {
        $product_id = $_REQUEST['add-to-cart'];
        $product_permalink = get_permalink($product_id);

        // If the product URL is available, redirect to it
        if ($product_permalink) {
            return $product_permalink;
        }
    }

    // If the product URL is not available, redirect to the home page
    return home_url('/');
}
© www.soinside.com 2019 - 2024. All rights reserved.