我正在使用Woocommerce,需要以下信息:
是否可以将购物车项目限制为6个,并在超过此限制时显示一条消息?
发布于 2017-09-02 06:08:31
如果要限制购物车项目,有两个操作需要检查和控制:
使用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文件中,也可以放在任何插件文件中。
这段代码已经过测试,可以正常工作
发布于 2017-09-02 04:36:08
您可以在验证要添加到购物车的产品时添加其他验证参数。根据产品是否可以添加到购物车中,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 );
https://stackoverflow.com/questions/46007102
复制相似问题