Dynamic synched custom checkout select fields in WooCommerce

前端 未结 1 590
暗喜
暗喜 2021-01-07 09:31

In Woocommerce I have been able to add 2 custom dropdowns list in checkout page:

add_action(\'woocommerce_before_order_notes\', \'wps_add_select_checkout_         


        
1条回答
  •  醉话见心
    2021-01-07 09:49

    I have merged your 2 first functions as they use the same hook.

    In this merged function I have added:

    • The "required" option to both fields.
    • Changed the slugs for both fields as for example "City" throw a woocommerce error.
    • different sets of "options" arrays that I pass to javascript (one for each available in the first select field).
    • Some jQuery code that create dynamically the set of options in the 2nd select field, based on the selected of the first select field.

    I have change a bit the condition for the If statement in the last function.

    Here is the revisited code:

    // Add checkout custom select fields
    add_action( 'woocommerce_before_order_notes', 'add_checkout_custom_fields', 20, 1 );
    function add_checkout_custom_fields( $checkout) {
        $domain = 'woocommerce'; // The domain slug
    
        echo '

    '.__( 'Next Day Delivery', $domain ).'

    '; // First Select field (Master) woocommerce_form_field( 'delivery_one', array( 'type' => 'select', 'label' => __( 'Delivery options one' , $domain), 'class' => array( 'form-row-wide' ), 'required' => true, 'options' => array( '' => __( 'Please select a value', $domain ), 'A' => __( 'A', $domain ), 'B' => __( 'B', $domain ), 'C' => __( 'C', $domain ), ), ), $checkout->get_value( 'delivery_one' ) ); // Default option value $default_option2 = __( 'Please select a value', $domain ); // Dynamic select field options for Javascript/jQuery $options_0 = array( '' => $default_option2 ); $options_a = array( '' => $default_option2, 'D' => __( 'D', $domain ), 'E' => __( 'E', $domain ), 'F' => __( 'F', $domain ), 'G' => __( 'G', $domain ), ); $options_b = array( '' => $default_option2, 'H' => __( 'H', $domain ), 'I' => __( 'I', $domain ), 'J' => __( 'J', $domain ), ); $options_c = array( '' => $default_option2, 'K' => __( 'K', $domain ), 'L' => __( 'L', $domain ), 'M' => __( 'M', $domain ), ); // Second Select field (Dynamic Slave) woocommerce_form_field( 'delivery_two', array( 'type' => 'select', 'label' => __( 'Delivery options two', $domain ), 'class' => array( 'form-row-wide' ), 'required' => true, 'options' => $options_0, ), $checkout->get_value( 'delivery_two' ) ); $required = esc_attr__( 'required', 'woocommerce' ); // jQuery code ?> ' . $notice . '', 'error' ); } }

    Code goes in function.php file of your active child theme (active theme).

    This is a fully working and tested example.

    0 讨论(0)
提交回复
热议问题