限制 WooCommerce 购物车中允许的不同产品的数量
Limit the number of different products allowed in WooCommerce cart
使用 Limit the number of cart items in Woocommerce 答案,我可以限制商店购物车页面中的产品总数量。但我需要限制购物车中不同商品的数量,但要保持数量不受限制并限制为产品总价格。
例如我的购物车中有 10 件商品,但产品总数量为 50,产品总价格为 5000。
如果我在购物车 10 中设置了不同的产品数量并且总价为 5000,我的客户将无法将另一产品添加到他们的购物车。
我该怎么做?
您可以使用以下方法来限制允许添加到购物车的不同产品的数量:
// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_n_products_allowed_in_cart', 10, 3 );
function only_n_products_allowed_in_cart( $passed, $product_id, $quantity ) {
$items_limit = 10;
$total_count = count( WC()->cart->get_cart() ) + 1;
if( $total_count > $items_limit ){
// Set to false
$passed = false;
// Display a message
wc_add_notice( sprintf( __( "You can’t have more than %s different products in cart", "woocommerce" ), $items_limit ), "error" );
}
return $passed;
}
代码进入活动子主题(或活动主题)的 functions.php 文件。
使用 Limit the number of cart items in Woocommerce 答案,我可以限制商店购物车页面中的产品总数量。但我需要限制购物车中不同商品的数量,但要保持数量不受限制并限制为产品总价格。
例如我的购物车中有 10 件商品,但产品总数量为 50,产品总价格为 5000。 如果我在购物车 10 中设置了不同的产品数量并且总价为 5000,我的客户将无法将另一产品添加到他们的购物车。
我该怎么做?
您可以使用以下方法来限制允许添加到购物车的不同产品的数量:
// Checking and validating when products are added to cart
add_filter( 'woocommerce_add_to_cart_validation', 'only_n_products_allowed_in_cart', 10, 3 );
function only_n_products_allowed_in_cart( $passed, $product_id, $quantity ) {
$items_limit = 10;
$total_count = count( WC()->cart->get_cart() ) + 1;
if( $total_count > $items_limit ){
// Set to false
$passed = false;
// Display a message
wc_add_notice( sprintf( __( "You can’t have more than %s different products in cart", "woocommerce" ), $items_limit ), "error" );
}
return $passed;
}
代码进入活动子主题(或活动主题)的 functions.php 文件。