how to activate woocommerce rate shipping 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', 'shipping_cost_based_on_weight', 12, 2);
function shipping_cost_based_on_weight( $rates, $package ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
$cost1 = 5;
$cost2 = 9;
$cost3 = 9;
$total_weight = WC()->cart->get_cart_contents_weight();
foreach ( $rates as $rate_key => $rate ){
$has_taxes = false;
if( 'flat_rate' === $rate->method_id ){
$initial_cost = $new_cost = $rates[$rate_key]->cost;
if( $total_weight <= 6 ) {
$new_cost = $cost1;
}
elseif( $total_weight > 6 && $total_weight <= 12 ) {
$new_cost = $cost2;
}
else {
$new_cost = $cost3;
}
$rates[$rate_key]->cost = $new_cost;
$taxes = [];
foreach ($rates[$rate_key]->taxes as $key => $tax){
if( $rates[$rate_key]->taxes[$key] > 0 ){
$initial_tax_cost = $new_tax_cost = $rates[$rate_key]->taxes[$key];
$tax_rate = $initial_tax_cost / $initial_cost;
$taxes[$key] = $new_cost * $tax_rate;
$has_taxes = true;
}
}
if( $has_taxes )
$rates[$rate_key]->taxes = $taxes;
}
}
return $rates;
}