I'm using WordPress 5.0.2
with WooCommerce 3.5.3
and I have a custom select dropdown field with optgroup on the checkout page, the field work as expected but it appear after the order note and I would like that it appear below the billing_country
field.
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>';
}
The code comes this previous thread: WooCommerce Select Dropdown With Optgroup On Checkout
I'm aware that this custom field is not hooked to the woocommerce_checkout_fields
, And if I do so, it doesn't show the field because I guess that this custom select field is not pulled from the class-wc-countries.php
.
This code is required for this answer.
Now you will be able to include a custom select field with option groups in Woocommerce form fields like checkout billing and shipping fields.
Here is that code for your Billing and shipping region field:
Code goes in function.php file of your active child theme (or active theme). Tested and works.
Related: WooCommerce Select Dropdown With Optgroup On Checkout