Gravity Forms Create Optgroups to Separate Select Options
Gravity Forms Create Optgroups to Separate Select Options
Gravity Forms is another plugin that I leverage on the majority of sites I develop. It’s well developed, well maintained, and has all the necessary features you would expect from a form builder. While I was building a Gravity Form the other day, I had the need to create Optgroups within the default Drop Down field. After doing a bit of searching, I stumbled across this great filter on Github.
/** * Filter Gravity Forms select field display to wrap optgroups where defined * USE: * set the value of the select option to `optgroup` within the form editor. The * filter will then automagically wrap the options following until the start of * the next option group */ add_filter( 'gform_field_content', 'filter_gf_select_optgroup', 10, 2 ); function filter_gf_select_optgroup( $input, $field ) { if ( $field->type == 'select' ) { $opt_placeholder_regex = strpos($input,'gf_placeholder') === false ? '' : "<\s*?option.*?class='gf_placeholder'>[^<>]+<\/option\b[^>]*>"; $opt_regex = "/<\s*?select\b[^>]*>" . $opt_placeholder_regex . "(.*?)<\/select\b[^>]*>/i"; $opt_group_regex = "/<\s*?option\s*?value='optgroup\b[^>]*>([^<>]+)<\/option\b[^>]*>/i"; preg_match($opt_regex, $input, $opt_values); $split_options = preg_split($opt_group_regex, $opt_values[1]); $optgroup_found = count($split_options) > 1; // sometimes first item in the split is blank if( strlen($split_options[0]) < 1 ){ unset($split_options[0]); $split_options = array_values( $split_options ); } if( $optgroup_found ){ $fixed_options = ''; preg_match_all($opt_group_regex, $opt_values[1], $opt_group_match); if( count($opt_group_match) > 1 ){ foreach( $split_options as $index => $option ){ $fixed_options .= "<optgroup label='" . $opt_group_match[1][$index] . "'>" . $option . '</optgroup>'; } } $input = str_replace($opt_values[1], $fixed_options, $input); } } return $input; }
How do you use it? First, copy and paste the above code into your active themes function.php file.
From there, you will want to create a Drop Down field within your Gravity Form and make sure the checkbox that states ‘Show Values’ is ticked. Next, add the value ‘optgroup’ wherever you want to create a new options group.
The result is a beautiful and more importantly, organized select drop down:
Not workin with the latest verstion.
Yes not working in latest version. How can I get it to work in the latest version??