[英]Allow only one product purchase for a specific product category in Woocommerce
[英]Only allow to purchase one Item In Woocommerce 3
無論如何,是否可以防止在 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' );
已更新(在您的評論中提出了第二個替代方案)。
下面的代碼將添加到購物車限制為在添加多個時顯示錯誤消息的唯一項目。 第二個功能將檢查購物車項目,避免結賬並在有多個項目時添加錯誤消息:
// 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 文件中。 測試和工作。
上面的代碼片段似乎對我不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.