plugin development - Show special field when correct shipping is chosen

admin2025-06-03  10

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...

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...

Share Improve this question asked Jan 24, 2019 at 17:47 Pavel JanicekPavel Janicek 2123 silver badges14 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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;

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748964594a315211.html

最新回复(0)