是否要防止在WooCommerce中购买多个项目,还是要防止多个项目添加到购物车中?
我有不同的产品,但我想只允许一个项目每次结账。
我试图搜索解决方案,但那些现有的解决方案不能正常工作,假设用户没有登录并将项目添加到购物车中,然后在那里进行签出和登录--之前在客户登录时添加的项--也加到了刚才添加的一个客户,所以现在购物车中有两个产品,这就是我使用的代码中的一个问题,它不能正常工作。
function woo_custom_add_to_cart( $cart_item_data ) {
global $woocommerce;
$woocommerce->cart->empty_cart();
return $cart_item_data;
}
add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );发布于 2018-07-28 23:37:56
更新(在你的评论中有第二种选择)。
下面的代码将限制添加到购物车在添加多个错误消息时显示错误信息的唯一项。第二个函数将检查购物车项,避免签出,并在有多个项时添加错误消息:
// Allowing adding only one unique item to cart and displaying an error message
add_filter( 'woocommerce_add_to_cart_validation', 'add_to_cart_validation', 10, 1 );
function add_to_cart_validation( $passed ) {
if( ! WC()->cart->is_empty() ){
wc_add_notice( __("You can add only one item to cart", "woocommerce" ), 'error' );
$passed = false;
}
return $passed;
}
// Avoiding checkout when there is more than one item and displaying an error message
add_action( 'woocommerce_check_cart_items', 'check_cart_items' ); // Cart and Checkout
function check_cart_items() {
if( sizeof( WC()->cart->get_cart() ) > 1 ){
// Display an error message
wc_add_notice( __("More than one items in cart is not allowed to checkout", "woocommece"), 'error' );
}
}代码在您的活动子主题(或活动主题)的functions.php文件中。测试和工作。
1)当尝试添加到购物车第二项时:

2)如果购物车中有多个项目:

3)在结帐中,您将得到一个带有相同错误通知的空页面:

若要只允许一个购物车项删除在任何情况下工作的任何附加项,请执行以下操作:
// Removing on add to cart if an item is already in cart
add_filter( 'woocommerce_add_cart_item_data', 'remove_before_add_to_cart' );
function remove_before_add_to_cart( $cart_item_data ) {
WC()->cart->empty_cart();
return $cart_item_data;
}
// Removing one item on cart item check if there is more than 1 item in cart
add_action( 'template_redirect', 'checking_cart_items' ); // Cart and Checkout
function checking_cart_items() {
if( sizeof( WC()->cart->get_cart() ) > 1 ){
$cart_items_keys = array_keys(WC()->cart->get_cart());
WC()->cart->remove_cart_item($cart_items_keys[0]);
}
}代码在您的活动子主题(或活动主题)的functions.php文件中。测试和工作。
https://stackoverflow.com/questions/51575669
复制相似问题