I had built an express checkout for one of my woocommerce store and I’m builting a functionality of 0 shipping charges for all prepaid orders. I have one checkbox to enable/disable COD in the checkout page and based on the selection of that checkbox I’m trying to toggle the shipping charges. I also want to reflect the changes on the checkout page frontend itself like it should show the shipping charges and refreshes the order total in the order summary only if COD is enabled else It should show 0 shipping charges & order total remains unchanged.
After some research I found one hook woocommerce_package_rates
that basically helps to tweak the shipping charges and I tried this:
add_action('woocommerce_package_rates', 'custom_woocommerce_zero_shipping_for_prepaid_orders', 10, 2);
function custom_woocommerce_zero_shipping_for_prepaid_orders($rates, $package) {
// Check for the chosen payment method
$chosen_payment_method = WC()->session->get('chosen_payment_method');
// If the chosen payment method is NOT 'cod' (Cash on Delivery), set shipping to zero
if ($chosen_payment_method !== 'cod') {
foreach ($rates as $rate_key => $rate) {
// Set the cost of each shipping method to zero
$rates[$rate_key]->cost = 0;
// If you want to also set taxes to zero, uncomment the line below
$rates[$rate_key]->taxes = array_map(function($tax) { return 0; }, $rates[$rate_key]->taxes);
}
}
return $rates;
}
But this hook triggers on page load. It might work for the calculations behind the scene post placing an order. But, I’m not able to hook this with custom ajax calls to recalculate the prices on the checkout page itself.
Is there any other way which can help to meet the expectations?
P.S: I already tried to make it work with coupons. I don’t want to implement this functionality by using coupons.
Any help is much appreciated. Thanks!