Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Last active November 15, 2017 20:38
Show Gist options
  • Save jtsternberg/78a8eab48fb0ebae7515 to your computer and use it in GitHub Desktop.
Save jtsternberg/78a8eab48fb0ebae7515 to your computer and use it in GitHub Desktop.
CMB2 select field options overridden with a filter and using optgroups
<?php
function cmb_opt_groups( $args, $defaults, $field_object, $field_types_object ) {
// Only do this for the field we want (vs all select fields)
if ( '_cmb_option_field' != $field_types_object->_id() ) {
return $args;
}
$option_array = array(
'Group 1' => array(
'group1-value1' => 'Value 1',
'group1-value2' => 'Value 2',
'group1-value3' => 'Value 3',
),
'Group 2' => array(
'group2-value1' => 'Value 1',
'group2-value2' => 'Value 2',
'group2-value3' => 'Value 3',
),
'Group 3' => array(
'group3-value1' => 'Value 1',
'group3-value2' => 'Value 2',
'group3-value3' => 'Value 3',
),
);
$saved_value = $field_object->escaped_value();
$value = $saved_value ? $saved_value : $field_object->args( 'default' );
$options_string = '';
$options_string .= $field_types_object->option( __( 'Select an Option', 'msft-newscenter' ), '', ! $value );
foreach ( $option_array as $group_label => $group ) {
$options_string .= '<optgroup label="'. $group_label .'">';
foreach ( $group as $key => $label ) {
$options_string .= $field_types_object->option( $label, $key, $value == $key );
}
$options_string .= '</optgroup>';
}
// Ok, replace the options value
$defaults['options'] = $options_string;
return $defaults;
}
add_filter( 'cmb2_select_attributes', 'cmb_opt_groups', 10, 4 );
@gyrus
Copy link

gyrus commented Jul 16, 2015

Thanks! Works well, apart from the option method is now select_option, and it takes an array of args. See https://gist.github.com/gyrus/480675f7bbd5d5aec6e0

@smhz101
Copy link

smhz101 commented Nov 15, 2017

hi, thanks for the snippet, but i am confused i am trying to use this snippet with in group, how can identify my group id

// Only do this for the field we want (vs all select fields)

if ( '_cmb_option_field' != $field_types_object->_id() ) {
	return $args;
}

thanks

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