[英]Limit the number of cart items in Woocommerce
我正在使用Woocommerce,需要以下內容:
由於產品被出售給另一個國家,並且該國家的海關僅允許總量為6,因此我需要阻止客戶訂購超過6種產品(產品)。
6是項目或產品的總和。 客戶可訂購1件產品,數量為6件或2件產品,每件3件。 海關只允許總數為6。
如果購物車中有超過6個商品,則會出現警告並阻止客戶繼續結帳。
是否可以將購物車商品限制為6並在超出此限額時顯示消息?
如果要限制購物車項目,則需要檢查和控制2個操作:
使用掛鈎在woocommerce_add_to_cart_validation
過濾器掛鈎中的自定義函數,您可以將購物車項目限制為最大6個,並在超出此限制時顯示自定義消息:
// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_six_items_allowed_add_to_cart', 10, 3 );
function only_six_items_allowed_add_to_cart( $passed, $product_id, $quantity ) {
$cart_items_count = WC()->cart->get_cart_contents_count();
$total_count = $cart_items_count + $quantity;
if( $cart_items_count >= 6 || $total_count > 6 ){
// Set to false
$passed = false;
// Display a message
wc_add_notice( __( "You can’t have more than 6 items in cart", "woocommerce" ), "error" );
}
return $passed;
}
使用掛鈎在woocommerce_update_cart_validation
過濾器掛鈎中的自定義功能,您可以控制購物車商品數量更新到您的6購物車商品限制,並在超出此限制時顯示自定義消息:
// Checking and validating when updating cart item quantities when products are added to cart
add_filter( 'woocommerce_update_cart_validation', 'only_six_items_allowed_cart_update', 10, 4 );
function only_six_items_allowed_cart_update( $passed, $cart_item_key, $values, $updated_quantity ) {
$cart_items_count = WC()->cart->get_cart_contents_count();
$original_quantity = $values['quantity'];
$total_count = $cart_items_count - $original_quantity + $updated_quantity;
if( $cart_items_count > 6 || $total_count > 6 ){
// Set to false
$passed = false;
// Display a message
wc_add_notice( __( "You can’t have more than 6 items in cart", "woocommerce" ), "error" );
}
return $passed;
}
代碼放在活動子主題(或主題)的function.php文件中,或者放在任何插件文件中。
此代碼經過測試和運行
驗證要添加到購物車的產品時,您可以添加其他驗證參數。 woocommerce_add_to_cart_validation
要求返回true
或false
值,具體取決於產品是否可以添加到購物車:
/**
* When an item is added to the cart, check total cart quantity
*/
function so_21363268_limit_cart_quantity( $valid, $product_id, $quantity ) {
$max_allowed = 6;
$current_cart_count = WC()->cart->get_cart_contents_count();
if( ( $current_cart_count > $max_allowed || $current_cart_count + $quantity > $max_allowed ) && $valid ){
wc_add_notice( sprint( __( 'Whoa hold up. You can only have %d items in your cart', 'your-plugin-textdomain' ), $max ), 'error' );
$valid = false;
}
return $valid;
}
add_filter( 'woocommerce_add_to_cart_validation', 'so_21363268_limit_cart_quantity', 10, 3 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.