Created
October 5, 2018 09:58
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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