John Davidson

php - WooCommerce: Shipping by Weight and cost

0 comments
Message:


I would like to get a shipping price per kilo from 1 kilo to 10 prices, and from 11 kilos to 20 prices, but if the amount is above $100, the shipping will be free and I don’t have to calculate the price of the kilo, I try to add that when the total purchase is $100 The shipping account is cancelled, but I could not, can you help, thank you?


add_filter( 'woocommerce_package_rates', 'binary_carpenter_weight_based_shipping_tiers', 10, 16 );

function binary_carpenter_weight_based_shipping_tiers( $rates, $package ) {


if ( WC()->cart->cart_contents_weight <= 10 ) {

foreach($rates as $key => $value)
{
if ($value->cost != 4.49 && $value->method_id != 'local_pickup')
unset($rates[$key]);

}

} elseif ( WC()->cart->cart_contents_weight <= 16 ) {

foreach($rates as $key => $value)
{
if ($value->cost != 10 && $value->method_id != 'local_pickup')
unset($rates[$key]);

}

} if ($value->cost != 100 && $value->method_id != 'local_pickup'){

unset($rates['flat_rate:12']);
unset($rates['flat_rate:15']);

}

return $rates;

}



My Answer:
>cart->get_cart_contents_total() > 100 ) {
// If total purchase is above $100, set shipping cost to 0
foreach ( $rates as $rate_key => $rate ) {
$rates[$rate_key]->cost = 0;
}
} else {
// Calculate shipping cost based on weight
$total_weight = 0;
foreach ( $package['contents'] as $item_id => $values ) {
$_product = $values['data'];
$total_weight += $_product->get_weight() * $values['quantity'];
}

if ( $total_weight >= 1 && $total_weight <= 10 ) {
// Set shipping cost per kilo for weight range 1-10
foreach ( $rates as $rate_key => $rate ) {
$rates[$rate_key]->cost = $total_weight * 10; // Change 10 to your desired cost per kilo
}
} elseif ( $total_weight >= 11 && $total_weight <= 20 ) {
// Set shipping cost per kilo for weight range 11-20
foreach ( $rates as $rate_key => $rate ) {
$rates[$rate_key]->cost = $total_weight * 8; // Change 8 to your desired cost per kilo
}
}
}

return $rates;
}

Rate this post

5 of 5 based on 4496 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us