![](/img/trans.png)
[英]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.