WooCommerce Select Dropdown With Optgroup On Checkout

会有一股神秘感。 提交于 2019-12-13 02:36:13

问题


I'm using WordPress 5.0.2 with WooCommerce 3.5.3 and I have created a select dropdown on the checkout page, it works good, however I want to add some options groups into it to organized the select options

Here is my code from my functions.php :

add_action('woocommerce_before_order_notes', 'add_select_checkout_field');
function add_select_checkout_field( $checkout ) {
  echo '<p>New Select Dropdown</p>';
  woocommerce_form_field( 'region', array(
      'type'          => 'select',
      'class'         => array( 'region-dropdown' ),
      'label'         => __( 'Select your region' ),
      'options'       => array(
          'region1'   => __( 'Region 1', 'woocommerce' ),
          'region2' => __( 'Region 2', 'woocommerce' ),
          'region3' => __( 'Region 3', 'woocommerce' ),
          'region4'   => __( 'Region 4', 'woocommerce' )
      )
 ),
  $checkout->get_value( 'region' ));
}

And I want to the result is outputed like this :

<select>
    <optgroup label="North Region">
        <option>Region 1</option>
        <option>Region 2</option>
    </optgroup>
    <optgroup label="South Region">
        <option>Region 3</option>
        <option>Region 4</option>
    </optgroup>
</select>

I don't know why woocommerce doesn't implement this functionality but I hope there is a way to do it.

Any help would be appreciated


回答1:


You can do it in 2 ways:

1) Enabling <optgoup> in Woocommerce select form fields, you can use from GitHub:

  • This new fresh thread: lomars - Woocommerce select form field with options group

  • This older thread: QWp6t - Add optgroup support to WooCommerce select form fields

2) Enabling <optgoup> manually in a select field like:

add_action('woocommerce_before_order_notes', 'custom_checkout_select_field_with_optgroup', 10, 1 );
function custom_checkout_select_field_with_optgroup( $checkout ) {
    $domain  = 'woocommerce';
    $title   = __("Region", $domain);
    $slug    = sanitize_title($title);
    $default = __("Select your region", $domain);
    $value   = $checkout->get_value($slug);

    // Region option data array with optgroup
    $options = array(
        __("North Region", $domain) => array(
            'region1' => __("Region 1", $domain),
            'region2' => __("Region 2", $domain),
        ),
        __("South Region", $domain) => array(
            'region3' => __("Region 3", $domain),
            'region4' => __("Region 4", $domain),
        )
    );

    // The field
    echo '<p class="form-row form-row-wide '.$slug.'-dropdown" id="'.$slug.'_field" data-priority="">
    <label for="'.$slug.'" class="">'.$title.'</label>
    <span class="woocommerce-input-wrapper">
    <select name="'.$slug.'" id="'.$slug.'" class="select " data-placeholder="" autocomplete="'.$slug.'">
    <option value="">'.$default.'</option>';

    // Loop through "optgroup"
    foreach( $options as $optgroup_label => $optgroup_options ) {
        echo '<optgroup label="'.$optgroup_label.'">';
        // Loop through "options" in the "optgroup"
        foreach( $optgroup_options as $key => $label ) {
            $selected = $value === $key ? ' selected="selected"': '';
            echo '<option value="'.$key.'"'.$selected.'>'.$label.'</option>';
        }
        echo '</optgroup>';
    }

    echo '</select></span></p>';
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


Related thread: Add a custom field bellow billing country in Woocommerce Checkout




回答2:


You can use this code it will works for you

add_filter('woocommerce_form_field_select', function ($html, $unused, $args, $value) {
if (empty($args['options'])) {
    return $html;
}
$option_groups = ['-' => []];
$options = '';
foreach ($args['options'] as $option_key => $option_text) {
    $option = array_map('trim', explode(':', $option_text));
    if (count($option) >= 2) {
        $option_groups[array_shift($option)][$option_key] = implode(':', $option);
    } else {
        $option_groups['-'][$option_key] = $option[0];
    }
}
foreach ($option_groups as $group => $option) {
    if ($group !== '-') $options .= '<optgroup label="' . esc_attr($group) . '">';
    foreach ($option as $option_key => $option_text) {
        if ($option_key === '') {
            // If we have a blank option, select2 needs a placeholder
            if (empty($args['placeholder'])) {
                $args['placeholder'] = $option_text ?: __( 'Choose an option', 'woocommerce' );
            }
            $custom_attributes[] = 'data-allow_clear="true"';
        }
        $options .= '<option value="' . esc_attr($option_key) . '" '. selected($value, $option_key, false) . '>' . esc_attr($option_text) . '</option>';
    }
    if ($group !== '-') $options .= '</optgroup>';
}
return preg_replace('/(?:<select[^>]+>)\\K(.*)(?:<\\/option>)/s',$options, $html);}, 10, 4);



回答3:


Piyush Dhanotiya, this is not work,

Warning: array_map(): Argument #2 should be an array on line:

$option = array_map('trim', explode(':', $option_text));

Warning: count(): Parameter must be an array or an object that implements Countable on line:

if (count($option) >= 2) {



来源:https://stackoverflow.com/questions/53942586/woocommerce-select-dropdown-with-optgroup-on-checkout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!