Skip to content

Instantly share code, notes, and snippets.

@aaemnnosttv
Created October 5, 2018 09:58
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaemnnosttv/72d0d34fad21d3f906ac9f3bdd61bd50 to your computer and use it in GitHub Desktop.
Save aaemnnosttv/72d0d34fad21d3f906ac9f3bdd61bd50 to your computer and use it in GitHub Desktop.
GravityForms filter to allow for grouping select choices into labelled groups using special choice options.
<?php
/**
* Filter for GravityForms to group select field choices by a special "optgroup" choice.
*
* Simply add a new choice with a value of 'optgroup' to the dropdown to start a group of options.
* All following choices will be grouped under it using its label for the group.
* Any number of groups can be created, as each optgroup choice will start a new group.
* Supports field placeholder & ungrouped options, but must be before the first group.
*
* This snippet can be added to your theme's functions.php, or a custom plugin.
*
* Inspired by https://gist.github.com/codearachnid/a06e13be7f01b81b838c
*
* @author Evan Mattson (@aaemnnosttv)
*/
add_filter('gform_field_content', function ($input, $field) {
if ('select' !== $field->type
|| ! preg_match('#value=[\'"]optgroup[\'"]#', $input)
|| ! preg_match('#<select[^>]*>(.*)</select>#', $input, $option_matches)
|| ! preg_match_all('#<option.*?/option>#', $all_options_html = $option_matches[1], $option_element_matches)
|| ! ($options = reset($option_element_matches))
) {
return $input;
}
$label = '';
$groups = [];
foreach ($options as $option) {
if (preg_match('#value=[\'"]optgroup[\'"][^>]*>(.*)</option>#', $option, $option_matches)) {
$label = $option_matches[1];
} else {
$groups[$label][] = $option;
}
}
$grouped_options = array_map(function ($options, $group_label) {
$html = join("\n", $options);
return $group_label ? "<optgroup label='$group_label'>$html</optgroup>" : $html;
}, $groups, array_keys($groups));
return str_replace($all_options_html, join('', $grouped_options), $input);
}, 10, 2);
@izzycart
Copy link

This works perfectly for Dropdown field but doesn't work for Product Field with Field type set to Dropdown. Please can this be done to work with product field with a dropdown field type

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