WooCommerce Select 结帐时带有 Optgroup 的下拉菜单

WooCommerce Select Dropdown With Optgroup On Checkout

我正在使用 WordPress 5.0.2WooCommerce 3.5.3,并且我在结帐页面上创建了一个 select 下拉菜单,效果很好,但是我想在其中添加一些选项组整理 select 个选项

这是我的代码 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' ));
}

我希望结果是这样输出的:

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

我不知道为什么 woocommerce 没有实现这个功能,但我希望有办法实现。

如有任何帮助,我们将不胜感激

您可以使用此代码,它适合您

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);

您可以通过两种方式完成:

1) 在 Woocommerce select 表单字段 中启用 <optgroup>,您可以使用 from GitHub:

2) 在 select 字段中手动启用 <optgoup>,例如:

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>';
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。


相关主题: