Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gyrus/480675f7bbd5d5aec6e0 to your computer and use it in GitHub Desktop.
Save gyrus/480675f7bbd5d5aec6e0 to your computer and use it in GitHub Desktop.
<?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->select_option( array(
'label' => __( 'Select an option' ),
'value' => '',
'checked' => ! $value
));
foreach ( $option_array as $group_label => $group ) {
$options_string .= '<optgroup label="'. $group_label .'">';
foreach ( $group as $key => $label ) {
$options_string .= $field_types_object->select_option( array(
'label' => $label,
'value' => $key,
'checked' => $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 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment