Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 );
@pasqualevitiello

This comment has been minimized.

Copy link

commented Oct 8, 2014

It looks interesting but I can't really understand how to use that function. Would you please explain how to show such a metabox?

Thank you.

@gyrus

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.