如何设置每件产品的最大重量(不是每个订单)?
客户可以购买任意数量(数量)的产品,直到达到最大重量。如果他购买5件产品,每件产品的总重量不能达到最大重量。订单中可能有许多产品,但每个产品的总单位(数量)具有最大重量。
例如,在单个订单中:
答案 0 :(得分:1)
在下面的示例中,此钩子函数在添加到购物车操作时触发,您可以执行所有类型的检查以验证操作(并显示自定义错误消息)。
所以你会看到你可以单独定位总物品重量......
add_filter( 'woocommerce_add_to_cart_validation', 'custom_add_to_cart_validation', 20, 5 );
function custom_add_to_cart_validation( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {
// HERE define the weight limit per item
$weight_limit = 2; // 2kg
$total_item_weight = 0;
// Check cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
$item_product_id = empty($variation_id) ? $product_id : $variation_id;
// If the product is already in cart
if( $item_product_id == $cart_item['data']->get_id() ){
// Get total cart item weight
$total_item_weight += $cart_item['data']->get_weight() * $cart_item['quantity'];
}
}
// Get an instance of the WC_Product object
$product = empty($variation_id) ? wc_get_product($product_id) : wc_get_product($variation_id);
// Get total item weight
$total_item_weight += $product->get_weight() * $quantity;
if( $total_item_weight > $weight_limit ){
$passed = false ;
$message = __( "Custom warning message for weight exceed", "woocommerce" );
wc_add_notice( $message, 'error' );
}
return $passed;
}
您还需要一个额外的挂钩功能,该功能将在购物车数量更改时触发:
add_filter( 'woocommerce_after_cart_item_quantity_update', 'limit_cart_item_quantity', 20, 4 );
function limit_cart_item_quantity( $cart_item_key, $new_quantity, $old_quantity, $cart ){
// HERE define the weight limit per item
$weight_limit = 2; // 2kg
// Get an instance of the WC_Product object
$product = $cart->cart_contents[ $cart_item_key ]['data'];
$product_weight = $product->get_weight(); // The product weight
// Calculate the limit allowed max quantity from allowed weight limit
$max_quantity = floor( $weight_limit / $product_weight );
// If the new quantity exceed the weight limit
if( ( $new_quantity * $product_weight ) > $weight_limit ){
// Change the quantity to the limit allowed max quantity
$cart->cart_contents[ $cart_item_key ]['quantity'] = $max_quantity;
// Add a custom notice
$message = __( "Custom warning message for weight exceed", "woocommerce" );
wc_add_notice( $message, 'notice' );
}
}
代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作