0

I'm trying to custom code the shopping cart in Woocommerce by changing the price of the delivery when a condition is met.

For example, if the product weighs 25kg, then simply add another price on top.

Here's my code in functions.php but it doesn't seem to work when i refresh the shopping cart.

$chosen_shipping_state = WC()->customer->get_shipping_postcode();
$chosen_state = $chosen_shipping_state;

// Get the selected shipping price
$chosen_shipping_method_price = WC()->session->get('cart_totals')['shipping_total'];

if ($cartweight >= 25 && $cartweight <= 50) {
        
        WC()->session->set('shipping_total', '100');
        do_action( 'woocommerce_cart_updated' );
        
}
        

So the current price of the selected courier is $5.50.

If the product weighs over 25 kgs, how do I made the courier price set to $11 and the shopping cart automatically refreshes with this amount?

Khoa
  • 261
  • 1
  • 2
  • 19

1 Answers1

1

First, you must choose shipping method ID.

Second, You need to put this code on your functions.php file inside your active theme directory. If your code is not working, please try to clear WooCommerce transient. In order to clear your WooCommerce transient, you can go to WooCommerce -> Status. Then click on Tools tab and you will see WooCommerce Transients. Click on the Clear Transients button.

add_filter( 'woocommerce_package_rates', 'override_ups_rates' );
function override_ups_rates( $rates ) {
    foreach( $rates as $rate_key => $rate ){
        // Check if the shipping method ID is UPS for example
        if( ($rate->method_id == 'flexible_shipping_ups') ) {
            // Set cost to zero
            $rates[$rate_key]->cost = 5.50;
        } 
    }
    return $rates;        
}
  • Thanks heaps!! It worked!!! :D One slight adjustment, I had to print_r($rates) so I can clearly see all the elements in the array. It turns out that the "method_id" didn't match, it had to match the "id" instead so therefore the code was if( ($rate->id == 'flexible_shipping_ups') ) { Thanks again! you the man! – Khoa Jul 10 '20 at 00:36