WooCommerce选择在Checkout时启用Optgroup的下拉菜单

时间:2018-12-27 09:19:08

标签: php wordpress select woocommerce optgroup

我将WordPress 5.0.2WooCommerce 3.5.3一起使用,并且在结帐页面上创建了一个select下拉列表,效果很好,但是我想在其中添加一些选项组以组织选择选项< / p>

这是我的 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为什么不实现此功能,但我希望有一种方法可以实现。

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:1)

您可以使用此代码,它将为您工作

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 :(得分:1)

您可以通过2种方式来做到这一点:

1)在Woocommerce中启用<optgoup>选择表单字段,您可以从GitHub使用:

2)在诸如以下的选择字段中手动启用<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>';
}

代码进入您的活动子主题(或活动主题)的function.php文件中。经过测试,可以正常工作。

enter image description here


相关主题:Add a custom field bellow billing country in Woocommerce Checkout

答案 2 :(得分:-1)

Piyush Dhanotiya,这行不通,

警告:array_map():参数2应该是在线上的数组:

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

警告:count():参数必须是在线上实现Countable的数组或对象:

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