Custom calculated shipping costs based on shipping class in WooCommerce

Solution:

Use following code

add_filter( 'woocommerce_package_rates', 'custom_shipping_rates_based_on_shipping_class', 11, 2 );
function custom_shipping_rates_based_on_shipping_class( $rates, $package ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE define your shipping class to find
    $class = array(206);

    // HERE define the shipping method to change rates for
    $shipping_rate_ids = array('flat_rate:5', 'flat_rate:6')

    // Initialising
    $found = false;
    $item_price = $item_qty = $rush_fee = $item_total = 0;

    // Loop through cart items
    foreach( $package['contents'] as $cart_item_key => $cart_item ) {
        $item_shipping_class_id = $cart_item['data']->get_shipping_class_id();

        if( in_array( $item_shipping_class_id, $class ) ){
            $item_price += $cart_item['data']->get_price(); // Sum line item prices that have target shipping class
            $item_qty += $cart_item['quantity']; // Sum line item prices that have target shipping class
            $item_total = $item_price * $item_qty;
            $rush_fee = $item_total * 0.2;
            $found = true;  // Target shipping class found
        } 
    }

    if( $found ) {
        // Loop through shipping rates
        foreach( $rates as $rate_key => $rate ) {
            if( in_array($rate_key, $shipping_rate_ids) ) {
                if( $item_total > 0 && $item_total < 200 ) {
                    if($rush_fee < 25) {
                        $rates[$rate_key]->cost = 25 + 18.99;
                    } else {
                        $rates[$rate_key]->cost = $rush_fee + 18.99;
                    }
                }
                elseif ( $item_total > 200 ) {
                    if($rush_fee < 25) {
                        $rates[$rate_key]->cost = 25;
                    } else {
                        $rates[$rate_key]->cost = $rush_fee;
                    }
                }
            }
        }
    }
    return $rates;
}

Code goes on function.php file of your active child theme (or theme). Tested and works.

Refresh the shipping caches: (required)

  1. This code is already saved on your active theme’s function.php file.
  2. The cart is empty
  3. In a shipping zone settings, disable / save any shipping method, then enable back / save.

Initial answer.

As $method is a stdClass instance Object and not a WC_Shipping_Rate instance Object, the method get_label() is not defined for it (doesn’t exist)Instead you can use the property label.

So you just need to replace in the template:

$label = $method->get_label();

By

$label = $method->label; 

This should stop this error and solve your issue.