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

问题描述

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

我发现 Custom Woocommerce product weight calculation from dimensions 答案代码完美无缺。

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

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:

要获取相关的运输方式费率 ID,例如 flat_rate:12,请使用浏览器代码检查器检查每个相关的单选按钮属性 {{ 1}} 喜欢:

enter image description here