1

I tried this approach:

add_action( 'woocommerce_review_order_before_payment', array( $this, 'my_custom_checkout_field') );
add_action('updated_checkout',array( $this, 'my_custom_checkout_field'));

public function my_custom_checkout_field(){

    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    $chosen_shipping = $chosen_methods[0];
    if($chosen_shipping == 'zasilkovna'){
        include_once('special-field.php');
    }
}

However, the special field does not appear when user clicks the shipping method. User needs to manually refresh the page, which is not good.

I need to hook myself on the ajax and show the field when correct shipping is clicked.

I know the jqery is firing the action, but am not quite sure how to hook on it...

1
+50

You need to setup the change event on the field:

$('select.shipping-field').on('change', function()) {
   $.post(
       ajaxurl, 
       {
           action: 'shipping_special',
           data: 'your data here..'
       }, 
       function(response){
           // The response should contain your special field HTML
       }
   );
});

You can pass the current shipping select option

Then your theme's functions.php file needs to have the action to return your special field, if the shipping is zasilkovna

add_action('wp_ajax_shipping_special', 'shipping_special_field' );
add_action('wp_ajax_nopriv_shipping_special', 'shipping_special_field' );

function shipping_special_field() {
    // Return your special field HTML here
}

See wp_ajax__requestaction, this tutorial from WPMUDev or this SO answer;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.