In a client WooCommerce web site, free shipping method is enabled for orders amount up to 250. I use the code below (from this answer), to hide other shipping rates when the order amount is over 250, except when there is heavy items in cart.
add_filter( 'woocommerce_package_rates', 'conditionally_hide_other_shipping_based_on_items_weight', 100, 1 );
function conditionally_hide_other_shipping_based_on_items_weight( $rates ) {
// targeted weight
$target_product_weight = 12;
$target_cart_amount = 250;
WC()->cart->subtotal_ex_tax >= $target_cart_amount ? $passed = true : $passed = false ;
// Iterating trough cart items to get the weight for each item
foreach(WC()->cart->get_cart() as $cart_item){
if( $cart_item['variation_id'] > 0)
$item_id = $cart_item['variation_id'];
else
$item_id = $cart_item['product_id'];
// Getting the product weight
$product_weight = get_post_meta( $item_id , '_weight', true);
if( !empty($product_weight) && $product_weight >= $target_cart_amount ){
$light_products_only = false;
break;
}
else $light_products_only = true;
}
// If 'free_shipping' method is available and if products are not heavy
// and cart amout up to the target limit, we hide other methods
$free = array();
foreach ( $rates as $rate_id => $rate ) {
if ( 'free_shipping' === $rate->method_id && $passed && $light_products_only ) {
$free[ $rate_id ] = $rate;
break;
}
}
return ! empty( $free ) ? $free : $rates;
}
But now, I would like to set a variable shipping amount that will be calculated in 2 ways:
- When order amount is below 250, the calculation will be 1 euro by kilo on the total order items weight.
- When order amount is up to 250, the calculation will be made on heavy items weight only (1 euro by kilo). If there is not heavy items, the free shipping rate is available.
How can I achieve this, as it’s a bit complicated?
Any track to follow?
I have tried some existing related plugins, but they aren't convenient for this case.
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…