Skip to content

Instantly share code, notes, and snippets.

@QWp6t
Created June 30, 2016 00:51
Show Gist options
  • Select an option

  • Save QWp6t/442f32bc0228fab94554894aa77fc6a0 to your computer and use it in GitHub Desktop.

Select an option

Save QWp6t/442f32bc0228fab94554894aa77fc6a0 to your computer and use it in GitHub Desktop.
Add optgroup support to WooCommerce select form fields
<?php
/**
* Plugin Name: Add optgroup support to WooCommerce select form fields
* Description: Converts <code>Group: Option</code> syntax in WooCommerce select form fields into <code>&lt;optgroup...&gt;&lt;option...&gt;</code>
* Author: QWp6t
* Author URI: https://qwp6t.me/
*/
/** NOTE: This shit was quickly hacked together. Worked for me. YMMV. */
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);
@QWp6t

QWp6t commented Jun 30, 2016

Copy link
Copy Markdown
Author

Before

imgur

After

Imgur

@Tusko

Tusko commented Dec 14, 2019

Copy link
Copy Markdown

Perfect!

Thank you

@Starlette

Copy link
Copy Markdown

Can you give an example array ?

@wbaxterh

wbaxterh commented Dec 3, 2020

Copy link
Copy Markdown

Worked straight outta the box for me, wanting to group custom shipping labels. Thanks G!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment