在Woocommerce 3中仅允许购买一件商品

时间:2018-07-28 22:16:36

标签: php wordpress woocommerce cart checkout

无论如何,是否可以阻止在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' );

1 个答案:

答案 0 :(得分:2)

更新了(根据您的评论的要求提供了第二种选择)。

以下代码将添加到购物车限制为一个唯一的项目,当添加多个项目时,该项目会显示错误消息。第二个功能将检查购物车中的物品,避免结帐,并在有多个物品时添加错误消息:

// 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)尝试将第二项添加到购物车时:

enter image description here

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

enter image description here

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

enter image description here


要仅允许一个购物车商品删除在任何情况下都可以使用的其他商品:

// 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文件中。经过测试,可以正常工作。