在 Woocommerce 中设置每个购物车商品的最大重量

Set max weight per cart item in Woocommerce

如何设置每件产品(不是每个订单)的最大重量?

客户可以购买任意数量(数量)的产品,直至达到最大重量。如果他购买了 5 件产品,每件产品的总重量达不到最大重量。订单中可以有很多产品,但每个产品的总单位(数量)具有最大重量。

例如,在单个订单中:

在此示例中,挂钩函数在添加到购物车操作时触发,您可以执行各种检查以验证操作是否有效(并显示自定义错误消息).

所以您会看到您可以单独定位商品总重量……

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 文件。已测试并有效。