Woocommerce get shipping cost in cart code example

Example 1: get current shipping method woocommerce

$rate_table = array();

$shipping_methods = WC()->shipping->get_shipping_methods();

foreach($shipping_methods as $shipping_method){
    $shipping_method->init();

    foreach($shipping_method->rates as $key=>$val)
        $rate_table[$key] = $val->label;
}

echo $rate_table[WC()->session->get( 'chosen_shipping_methods' )[0]];

Example 2: add shipping rate based on cart total woocommerce

add_filter( 'woocommerce_package_rates', 'tl_shipping_on_price', 10, 2 );
function tl_shipping_on_price( $rates, $package ) {
 
    $total = WC()->cart->cart_contents_total;
	//echo $total;
    if( $total <= 500 ) {
 
        unset( $rates['flat_rate'] );
        unset( $rates['free_shipping'] );
 
    } elseif ( $total > 500 && $total < 1000 ) {
 
        unset( $rates['local_delivery'] );
        unset( $rates['free_shipping'] );
 
    } else {
		unset( $rates['local_delivery'] );
        unset( $rates['flat_rate'] );
	}
 
    return $rates;
}

Tags:

Php Example