[英]Add to cart validation in WooCommerce based on attribute value and product quantity from the cart page
[英]Add to cart maximun quantity per product with validation in WooCommerce
我想限制添加到購物車按鈕,每個產品的最大數量為 10。 我希望客戶每個訂單的每個產品的購買數量不能超過 10 個。
這是代碼
add_filter( 'woocommerce_add_to_cart_validation', 'restrict_per_product_quantity' );
function restrict_per_product_quantity($cart_item_data) {
global $woocommerce;
$item_count = $woocommerce->cart->cart_contents_count;
if($item_count > 10) {
wc_add_notice( 'Sorry, Only 10 quantity per product per order is allowed. If you would like to order more please contact support.', 'error' );
return false;
}
return $cart_item_data;
}
問題是此代碼不適用於每個產品,它會檢查購物車,如果購物車中有 10 件商品,則會顯示錯誤。
woocommerce_add_to_cart_validation
包含 5 個您可以使用的參數function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Set max allowed
$max_allowed = 10;
// Error message
$message = 'max ' . $max_allowed . ' products allowed';
// quantity > max allowed || elseif = when cart not empty
if ( $quantity > $max_allowed ) {
wc_add_notice( __( $message, 'woocommerce' ), 'error' );
$passed = false;
} elseif ( ! WC()->cart->is_empty() ) {
// Get current product id
$product_id = $variation_id > 0 ? $variation_id : $product_id;
// Cart id
$product_cart_id = WC()->cart->generate_cart_id( $product_id );
// Find product in cart
$in_cart = WC()->cart->find_product_in_cart( $product_cart_id );
// True
if ( $in_cart ) {
// Get cart
$cart = WC()->cart->get_cart();
// Current quantity in cart
$quantity_in_cart = $cart[$product_cart_id]['quantity'];
// Condition: quanitity in cart + new add quantity greater than max allowed
if ( $quantity_in_cart + $quantity > $max_allowed ) {
wc_add_notice( __( $message, 'woocommerce' ), 'error' );
$passed = false;
}
}
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
使用這些掛鈎設置產品的最小和最大數量。
<?php
/*
* Changing the minimum quantity to 2 for all the WooCommerce products
*/
function woocommerce_quantity_input_min_callback( $min, $product ) {
$min = 2;
return $min;
}
add_filter( 'woocommerce_quantity_input_min', 'woocommerce_quantity_input_min_callback', 10, 2 );
/*
* Changing the maximum quantity to 5 for all the WooCommerce products
*/
function woocommerce_quantity_input_max_callback( $max, $product ) {
$max = 5;
return $max;
}
add_filter( 'woocommerce_quantity_input_max', 'woocommerce_quantity_input_max_callback', 10, 2 );
?>
[![enter image description here][1]][1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.