4
votes

So, the checkout page has Cash On Delivery & Direct Bank Transfer payment method. The goal is to make no shipping method available OR to make free shipping to be the only available method when the COD payment_method radio is checked. To make it happen, I need to unset existing jne_shipping shipping method.

I am adding a callback to the payment_method radio change event:

$('input[name=payment_method]').change(function() {
  // request update_checkout to domain.com/checkout/?wc-ajax=update_order_review
  $('body').trigger('update_checkout');
});

and the hook in php:

add_filter( 'woocommerce_available_shipping_methods', 'freeOnCOD', 10, 1 );
function freeOnCOD($available_methods)
{
    if ( isset( $_POST['payment_method'] ) && $_POST['payment_method'] === 'cod' ) {
        unset( $available_methods['jne_shipping'] );
    }

    return $available_methods;
}

But this filter hook does not even run. I also tried woocommerce_package_rates but still there was no effect.

Ofcourse, I checked the WooCommerce's hooks documentation too, but can't figure what is the correct hook that runs on update_checkout or update_order_review

Any help is appreciated.

1

1 Answers

8
votes

Action that is triggered is woocommerce_checkout_update_order_review

You can run your custom logic like this:

function name_of_your_function( $posted_data) {

    global $woocommerce;

    // Parsing posted data on checkout
    $post = array();
    $vars = explode('&', $posted_data);
    foreach ($vars as $k => $value){
        $v = explode('=', urldecode($value));
        $post[$v[0]] = $v[1];
    }

    // Here we collect chosen payment method
    $payment_method = $post['payment_method'];

    // Run custom code for each specific payment option selected
    if ($payment_method == "paypal") {
        // Your code goes here
    }

    elseif ($payment_method == "bacs") {
        // Your code goes here
    }

    elseif ($payment_method == "stripe") {
        // Your code goes here
    }
}

add_action('woocommerce_checkout_update_order_review', 'name_of_your_function');

I hope this helps!