Solution:
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:
// Custom function that returns the options data array for "Region" field
function wc_get_region_options_data( $domain ){
return [
'' => __("Choose an option…"),
__("North Region", $domain) => [
'region1' => __("Region 1", $domain),
'region2' => __("Region 2", $domain),
],
__("South Region", $domain) => [
'region3' => __("Region 3", $domain),
'region4' => __("Region 4", $domain),
'region5' => __("Region 5", $domain),
'region6' => __("Region 6", $domain),
],
__("East Region", $domain) => [
'region7' => __("Region 7", $domain),
'region8' => __("Region 8", $domain),
'region9' => __("Region 9", $domain),
],
];
}
// Custom function that returns the "Region" field data array
function wc_get_region_field( $fields, $group ){
$domain = 'woocommerce';
$options = wc_get_region_options_data( $domain );
$priority = (int) $fields[$group.'_country']['priority'];
$fields[$group.'_region'] = array(
'label' => __("Region", $domain),
'type' => 'select_og',
'class' => array( 'form-row-wide' ),
'required' => true,
'priority' => $priority + 5,
'options' => $options,
'clear' => true,
);
return $fields;
}
// Include region field in billing section after billing country
add_filter('woocommerce_billing_fields', 'region_select_billing_field_with_optgroup', 10, 1 );
function region_select_billing_field_with_optgroup( $billing_fields ) {
$billing_fields = wc_get_region_field( $billing_fields, 'billing' );
return $billing_fields;
}
// Include region field in shipping section after shipping country
add_filter('woocommerce_shipping_fields', 'region_select_shipping_field_with_optgroup', 10, 1 );
function region_select_shipping_field_with_optgroup( $shipping_fields ) {
$shipping_fields = wc_get_region_field( $shipping_fields, 'shipping' );
return $shipping_fields;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.