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
You can use this code it will works for you
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) {
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: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