Advertisement
Guest User

Untitled

a guest
Jun 28th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. /**
  2. * Filter Gravity Forms select field display to wrap optgroups where defined
  3. * USE:
  4. * set the value of the select option to `optgroup` within the form editor.
  5. * Optionally end the group by setting the option value to `optgroupend`. The
  6.  
  7. * filter will then automagically wrap the options following until the start of
  8. * the next option group
  9. */
  10.  
  11. add_filter( 'gform_field_content', 'filter_gf_select_optgroup', 10, 2 );
  12. function filter_gf_select_optgroup( $input, $field ) {
  13. if ( $field->type == 'select' ) {
  14. $opt_placeholder_regex = strpos($input,'gf_placeholder') === false ? '' : "<\s*?option.*?class='gf_placeholder'>[^<>]+<\/option\b[^>]*>";
  15. $opt_regex = "/<\s*?select\b[^>]*>" . $opt_placeholder_regex . "(.*?)<\/select\b[^>]*>/i";
  16. $opt_group_regex = "/<\s*?option\s*?value='optgroup\b[^>]*>([^<>]+)<\/option\b[^>]*>/i";
  17. $opt_group_regex_all = "/<\s*?option\s*?value='optgroup\b[^>]*>[^<>]+<\/option\b[^>]*>(.*?)<\s*?option\s*?value='optgroupend\b[^>]*>[^<>]+<\/option\b[^>]*>/i";
  18. $opt_group_regex_end = "/<\s*?option\s*?value='optgroupend\b[^>]*>([^<>]+)<\/option\b[^>]*>/i";
  19.  
  20. preg_match($opt_regex, $input, $opt_values);
  21. $split_options = preg_split($opt_group_regex, $opt_values[1]);
  22. $optgroup_found = count($split_options) > 1;
  23.  
  24. // sometimes first item in the split is blank
  25. if( strlen($split_options[0]) < 1 ){
  26. unset($split_options[0]);
  27. $split_options = array_values( $split_options );
  28. }
  29.  
  30. if( $optgroup_found ){
  31. $fixed_options = '';
  32. preg_match_all($opt_group_regex, $opt_values[1], $opt_group_match);
  33. if( count($opt_group_match) > 1 ){
  34. foreach( $split_options as $index => $option ){
  35.  
  36. $split_options_end = preg_split($opt_group_regex_end, $option);
  37. if( count($split_options_end) > 1 ){
  38. if (isset($split_options_end[1])) {
  39. $fixed_options .= "<optgroup label='" . $opt_group_match[1][0] . "'>" . $split_options_end[0] . '</optgroup>';
  40. $fixed_options .= $split_options_end[1];
  41. } else {
  42. $fixed_options .= $split_options_end[0];
  43. }
  44. } else {
  45. $fixed_options .= "<optgroup label='" . $opt_group_match[1][$index] . "'>" . $option . '</optgroup>';
  46. }
  47. }
  48. }
  49. $input = str_replace($opt_values[1], $fixed_options, $input);
  50. }
  51. }
  52.  
  53. return $input;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement