Skip to content

Instantly share code, notes, and snippets.

@guytzhak
Created February 15, 2022 08:49
Show Gist options
  • Save guytzhak/383e136f1a89d3c542dbcf47541c8665 to your computer and use it in GitHub Desktop.
Save guytzhak/383e136f1a89d3c542dbcf47541c8665 to your computer and use it in GitHub Desktop.
Woocommerce Shipping based rate
add_filter( 'woocommerce_package_rates', 'ras_custom_shipping_costs', 20, 2 );
function ras_custom_shipping_costs( $rates, $package ) {
$weights_prices_field = get_field('shipping_weights', 'options');
$weights_prices = [];
foreach ($weights_prices_field as $weights_price) {
$weights_prices[floatval($weights_price['weight'])] = floatval($weights_price['price']);
}
foreach( $rates as $rate_key => $rate ){
if( $rate->method_id == 'flat_rate'){
$new_cost = $rates[$rate_key]->cost;
$cart_weight = WC()->cart->get_cart_contents_weight();
foreach ($weights_prices as $weight => $price) {
if($cart_weight > $weight )
$new_cost = $price;
}
$rates[$rate_key]->cost = $new_cost;
}
}
return $rates;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment