phpwoocommercedimensionshipping-method

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


I am trying to set up a dimensional weight counting method when the dimensional weight (width x height x length) of the product is greater than the weight (actual weight).

I found Custom Woocommerce product weight calculation from dimensions answer code that works perfectly.

However I would like to make it works only for specific shipping method(s). Any advice or help?

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;
}

Solution

  • You can use the following targeting specific shipping methods only (see at the end, how to get your shipping method rate ids):

    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;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.


    How to get the shipping method rate 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:

    enter image description here