我正在使用 Woocommerce 并需要以下内容:
由于产品正在销售到另一个国家,而那个国家的海关只允许总共 6 个,所以我需要防止客户订购超过 6 个项目(产品)。
6 是项目或产品的总数。客户可以订购 1 件产品,数量为 6 或 2 件产品,每件数量为 3。海关只允许物品总数为 6 件。
如果购物车中有超过 6 件商品,则会出现警告并阻止客户继续结帐。
这是否可以将购物车项目限制为 6 个并在超出此限制时显示一条消息?
我正在使用 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 );