[英]Add to cart validation in WooCommerce based on attribute value and product quantity from the cart page
Actually, I am trying to set a limit for adding to cart for some product ids based on product attribute.实际上,我正在尝试根据产品属性为某些产品 ID 设置添加到购物车的限制。
What i've done is:我所做的是:
add_action( 'woocommerce_add_to_cart_validation', 'max_add_to_cart', 10, 2 );
function max_add_to_cart( $cart_item_key, $product_id ) {
$product = wc_get_product( $product_id );
$maxqty = $product->get_attribute('quantite_max');
$nbcart = get_item_qty_cart($product_id);
if (!empty($maxqty) && $maxqty <= $nbcart) {
wc_add_notice("cant have more than " . " {$maxqty} x {$product->get_title()} in cart.", 'error');
return false;
}
return true;
}
It works in a loop, but on the product page, it doesn't take into account quantity input.它循环工作,但在产品页面上,它不考虑数量输入。
Is there a way to get quantity add input in my function?有没有办法在我的函数中获取数量添加输入?
woocommerce_add_to_cart_validation
contains 5 parameters (the last 2 are optional) woocommerce_add_to_cart_validation
包含 5 个参数(最后 2 个是可选的)
$passed
= return true by default $passed
= 默认返回真$product_id
= the product id, this gives you access to wc_get_product( $product_id )
to get the product object $product_id
= 产品 id,这使您可以访问wc_get_product( $product_id )
以获取产品对象$quantity
= current quantity you want to add to the cart $quantity
= 您要添加到购物车的当前数量get_item_qty_cart
does not seem to exist in your code您的代码中似乎不存在
get_item_qty_cart
Explanation via comment tags added in my answer通过在我的答案中添加的评论标签进行解释
So you get:所以你得到:
function filter_woocommerce_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = null, $variations = null ) {
// Get product object
$product = wc_get_product( $product_id );
// Flag
$flag = false;
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
// Get the product attribute value
$max_qty = $product->get_attribute( 'quantite_max' );
// NOT empty
if ( ! empty( $max_qty ) ) {
// If new added quantity greater than max quantity
if ( $quantity > $max_qty ) {
$flag = true;
// WC Cart NOT null & Cart is NOT empty
} elseif ( ! is_null( WC()->cart ) && ! WC()->cart->is_empty() ) {
// Get cart items quantities
$cart_item_quantities = WC()->cart->get_cart_item_quantities();
// Product quantity in cart
$product_qty_in_cart = isset( $cart_item_quantities[ $product_id ] ) ? $cart_item_quantities[ $product_id ] : null;
// New added quantity + product quantity in cart greater than max quantity
if ( ( $quantity + $product_qty_in_cart ) > $max_qty ) {
$flag = true;
}
}
}
}
// True
if ( $flag ) {
wc_add_notice( sprintf( __( 'Cant have more than %s x %s in cart', 'woocommerce' ), $max_qty, $product->get_name() ), 'error' );
$passed = false;
}
return $passed;
}
add_filter( 'woocommerce_add_to_cart_validation', 'filter_woocommerce_add_to_cart_validation', 10, 5 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.