我无法想象如何验证购物车内部是否有某些产品。我只需要允许一个产品结账。
以下是class-wc-cart.php中使用的代码,如果THE SAME产品已经在购物车中,则可以防止添加产品,我确定应该非常相似,但我是缺少一些WP变量来定义任何类型的产品。 我也尝试使用this code,但它在functions.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 "%s" to your cart.', 'woocommerce' ), $product_data->get_title() )
), 'error' );
return false;
}
}
谢谢。
答案 0 :(得分:1)
不要直接在woocommerce核心文件中进行更改,因为当您更新插件时,您的代码可能会丢失。
将以下代码添加到functions.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;
}
}
答案 1 :(得分:0)
是过滤器/挂钩,在项目添加到购物车之前运行,因为每个产品在添加之前都经过验证。
因此,在验证产品时,我们可以检查项目是否已经存在购物车中的商品并清除(如果能够添加当前商品)并添加错误消息。
/**
* When an item is added to the cart, remove other products
*/
function so_27030769_maybe_empty_cart( $valid, $product_id, $quantity ) {
if( ! empty ( WC()->cart->get_cart() ) && $valid ){
WC()->cart->empty_cart();
wc_add_notice( 'Whoa hold up. You can only have 1 item in your cart', 'error' );
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'so_27030769_maybe_empty_cart', 10, 3 );