WooCommerce Select Dropdown With Optgroup On Checkout

后端 未结 2 509
南旧
南旧 2020-12-20 07:27

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

2条回答
  •  生来不讨喜
    2020-12-20 08:30

    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 .= '';
        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 .= '';
        }
        if ($group !== '-') $options .= '';
    }
    return preg_replace('/(?:]+>)\\K(.*)(?:<\\/option>)/s',$options, $html);}, 10, 4);
    

提交回复
热议问题