tat*_*fox 2 php wordpress checkout cart woocommerce
是否有办法阻止在 WooCommerce 中购买多于一件商品,或阻止多于一件商品添加到购物车?
我有不同的产品,但我希望每次结账时只允许购买一件商品。
我尝试搜索解决方案,但那些现有的解决方案无法正常工作,假设当用户未登录并将商品添加到购物车中,然后转到结账并登录时,客户登录时也添加了之前添加的商品加起来就是刚刚添加的一个客户,所以现在购物车中有 2 个产品,这是一个问题,我正在使用的代码无法正常工作。
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' );
Run Code Online (Sandbox Code Playgroud)
已更新(按照您的评论中的要求提供了第二种选择)。
下面的代码将限制添加到购物车为唯一的商品,在添加多个商品时显示错误消息。第二个函数将检查购物车物品,避免结帐并在有多个物品时添加错误消息:
// 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' );
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的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]);
}
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。