仅针对特定运输方式从尺寸计算自定义 Woocommerce 产品重量

Custom Woocommerce product weight calculation from dimensions only for specific shipping methods

我正在尝试设置当产品的体积重量(宽x高x长)大于重量(实际重量)时的体积重量计算方法。

我发现 答案代码非常有效。

但是我想让它只适用于特定的运输方式。 有什么建议或帮助吗?

add_filter( 'woocommerce_product_get_weight', 'custom_get_weight_from_dimensions', 10, 2 );
function custom_get_weight_from_dimensions( $weight, $product ) {
    $chosen_shipping  = WC()->session->get('chosen_shipping_methods')[0]; 

    // How to restrict to specific shipping methods?

    $dim_weight = $product->get_length() * $product->get_width() * $product->get_height() / 5000;
    return $dim_weight > $weight ? $dim_weight : $weight;
}

您只能使用以下定向特定送货方式(请参阅最后,如何获取您的送货方式费率 ID)

add_filter( 'woocommerce_product_get_weight', 'custom_get_weight_from_dimensions', 10, 2 );
function custom_get_weight_from_dimensions( $weight, $product ) {
    if ( ! is_admin() ) {
        // Here set your targeted shipping method rate Ids
        $targetted_shipping_ids  = array( 'flat_rate:12', 'flat_rate:14' );
        
        // Get chosen shipping method(s)
        $chosen_shipping_methods  = (array) WC()->session->get('chosen_shipping_methods'); 
        $matched_shipping_methods = array_intersect( $chosen_shipping_methods, $targetted_shipping_ids );
        
        if( ! empty($matched_shipping_methods) ) {
            $dim_weight = $product->get_length() * $product->get_width() * $product->get_height() / 5000;
        }
    }

    return isset($dim_weight) && $dim_weight > $weight ? $dim_weight : $weight;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。已测试并有效。


如何获取送货方式费率ID:

To get the related shipping methods rate IDs, something like flat_rate:12, inspect with your browser code inspector each related radio button attribute value like: