如果产品在Woocommerce的购物车中,请删除添加到购物车按钮[重复]

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

如何才能将特定产品添加到购物车中?

或者如果产品已经在购物车中,有没有办法重定向到购物车页面

我在这里找到了解决方案,因为它不起作用

Disable Woocommerce add to cart button if the product is already in cart

如何才能为所有产品而不仅仅是单个产品?

php wordpress woocommerce product cart
1个回答
1
投票

此功能将检查您的产品是否已在购物车中。如果是这样,它将重定向到购物车页面。如果要直接重定向到结帐,请参阅代码中的注释。

只需将以下内容放在functions.php中即可。

经过测试和工作。

function check_if_product_in_cart($valid, $product_id, $quantity) {
    global $woocommerce;
    if($woocommerce->cart->cart_contents_count > 0){
        foreach($woocommerce->cart->get_cart() as $key => $val ) {
            $_product = $val['data'];
            if($product_id == $_product->id ) {
                // $url = WC()->cart->get_checkout_url(); // Checkout
                $url = wc_get_cart_url();  // Cart
                wp_redirect($url);
                exit;
            }
        }
    }
    return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_product_in_cart',11,3);
© www.soinside.com 2019 - 2024. All rights reserved.