结帐单个产品:验证购物车中是否有任何产品,并提供错误信息 [英] Checkout with a single product: verify if ANY product is in the cart, and give error

查看:66
本文介绍了结帐单个产品:验证购物车中是否有任何产品,并提供错误信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法想象如何验证购物车中是否装有某些产品。我只需要允许一种产品付款即可。

I can't imagine how to verify if the cart has some products inside, or not. I just need to allow ONE product for the checkout.

这是class-wc-cart.php中使用的代码,以防止在购物车中已经有相同产品的情况下添加产品,我敢肯定,非常相似,但是我缺少一些WP变量来定义任何一种产品。
我也尝试了此代码,但在functions.php中不起作用(不,我没有使用子主题)。

Here is the code used in class-wc-cart.php to prevent products to be added if THE SAME product is already in the cart, and I'm sure should be pretty similar, but I'm missing some WP variables to define any kind of product. I tried also with this code, but it doesn't work in functions.php (no, I'm not using child themes).

if ( $product_data->is_sold_individually() ) {
            $in_cart_quantity = $cart_item_key ? $this->cart_contents[ $cart_item_key ]['quantity'] : 0;

            // If it's greater than 0, it's already in the cart
            if ( $in_cart_quantity > 0 ) {
                wc_add_notice( sprintf(
                    '<a href="%s" class="button wc-forward">%s</a> %s',
                    $this->get_cart_url(),
                    __( 'View Cart', 'woocommerce' ),
                    sprintf( __( 'You cannot add another &quot;%s&quot; to your cart.', 'woocommerce' ), $product_data->get_title() )
                ), 'error' );
                return false;
            }
        }

谢谢。

推荐答案

不要直接在woocommerce核心文件中进行更改,因为在更新插件时,您的代码可能会丢失。

Don't make changes directly in woocommerce core file because when you update plugin, might your code lost.

将以下代码添加到functions.php中,它将仅将一种产品添加到购物车中:

Add following code into functions.php and it will add only one product into cart:

add_filter( 'woocommerce_add_to_cart_validation', 'woocommerce_add_cart_item_data_custom' );

function woocommerce_add_cart_item_data_custom( $cart_item_data ) {

    global $woocommerce;
    if($woocommerce->cart->cart_contents_count > 0){
         wc_add_notice(
                     __( 'You cannot add another product to your cart.', 'woocommerce' ));

                return false;
    }
}

这篇关于结帐单个产品:验证购物车中是否有任何产品,并提供错误信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆