使用单个产品结帐:验证购物车中是否有任何产品,并给出错误


Checkout with a single product: verify if ANY product is in the cart, and give error

我无法想象如何验证购物车内部是否有一些产品。我只需要允许一个产品结账。

这是class-wc-cart中使用的代码.php以防止在购物车中已经存在相同的产品时添加产品,我确信应该非常相似,但是我缺少一些WP变量来定义任何类型的产品。我也尝试使用此代码,但它在函数中不起作用.php(不,我没有使用子主题)。

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核心文件中进行更改,因为当您更新插件时,您的代码可能会丢失。

将以下代码添加到函数中.php它将仅将一个产品添加到购物车中:

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;
    }
}