How To Create CMB2 Switch Button Meta Field Type

  • Update On January 23rd, 2017
  • in WordPress
CMB2 Switch Button Field Type 800x249 - How To Create CMB2 Switch Button Meta Field Type

This post was last updated on January 23rd, 2017 at 06:16 pm

Custom Meta Boxes (CMB) is a developer's toolkit helps you in building meta boxes, custom fields, and forms for WordPress that will blow your mind. It was developed by Justin Sternberg of WebDevStudios. Using CMB is a great way to give your website exactly what you need, as the options are endless. It helps to customize the admin so that the client doesn’t have to format content to match your theme’s styles.

CMB2 is a complete rewrite of Custom Metaboxes and Fields for WordPress

Though there are lots of community made fields out there for extending it with more functionality! Sometimes you may look for a very specific field that doesn’t fit in with any other fields built into CMB2. Let’s say we want to make a CMB2 Switch Button. Here I will show how to create switch field in CMB2.

Making The CMB2 Switch Button Meta Field

it is very simple to build your own fields using CMB2’s built in field creation methods. To define your field markup, you need to hook into the ‘cmb2_render_{field-type}’ action. Based on that, our action to hook into is ‘cmb2_render_switch’.

/* CMB2 Switch Field. Add the code below in a file named switch_metafield.php ------------- */
function cmb2_render_switch( $field, $escaped_value, $object_id, $object_type, $field_type_object ) {
	$switch = '<div class="cmb2-switch">';
	$conditional_value =(isset($field->args['attributes']['data-conditional-value'])?'data-conditional-value="' .esc_attr($field->args['attributes']['data-conditional-value']).'"':'');
    $conditional_id =(isset($field->args['attributes']['data-conditional-id'])?' data-conditional-id="'.esc_attr($field->args['attributes']['data-conditional-id']).'"':'');
    $label_on =(isset($field->args['label'])?esc_attr($field->args['label']['on']):'On');
    $label_off =(isset($field->args['label'])?esc_attr($field->args['label']['off']):'Off');
    $switch .= '<input '.$conditional_value.$conditional_id.' type="radio" id="' . $field->args['_id'] . '1" value="1"  '. ($escaped_value == 1 ? 'checked="checked"' : '') . ' name="' . esc_attr($field->args['_name']) . '" />
		<input '.$conditional_value.$conditional_id.' type="radio" id="' . $field->args['_id'] . '2" value="0" '. (($escaped_value == '' || $escaped_value == 0) ? 'checked="checked"' : '') . ' name="' . esc_attr($field->args['_name']) . '" />
		<label for="' . $field->args['_id'] . '1" class="cmb2-enable '.($escaped_value == 1?'selected':'').'"><span>'.$label_on.'</span></label>
		<label for="' . $field->args['_id'] . '2" class="cmb2-disable '.(($escaped_value == '' || $escaped_value == 0)?'selected':'').'"><span>'.$label_off.'</span></label>';

	$switch .= '</div>';
	$switch .= $field_type_object->_desc( true );
	echo $switch;
}add_action( 'cmb2_render_switch', 'cmb2_render_switch', 10, 5 );

Styling The Field as Switch Button

After defining the field we need to style the field to look like a switch button.

/* CMB2 Switch Styling. Add the code below in a file named switch_metafield.css ------------- */
.cmb2-switch{ margin-right: 15px; margin-bottom: 5px; float: left; }
.cmb2-switch label { cursor: pointer; }
.cmb2-switch input { display: none; }
.cmb2-enable, .cmb2-disable { background: #F5F5F5; color: #95999d; border: 1px solid #bfbfbf; display: block; float: left; }
.cmb2-enable {border-radius: 3px 0 0 3px; border-right: 0 none; }
.cmb2-disable { border-left: 0 none; border-radius: 0 3px 3px 0; }
.cmb2-enable span, .cmb2-disable span { line-height: 30px; display: block; font-weight: normal; white-space: nowrap; padding: 0 10px; }
.cmb2-disable.selected { background-color: #bfbfbf; background-image: none; border-color: #bfbfbf; color: #fff;}
.cmb2-enable.selected { background-color: #005077; background-image: none; border-color: #005077; box-shadow: none; color: #fff; }

Enabling the click event for the CMB2 Switch Button

After defining and styling the field we need to enable the click event to feel like its a switch button. So I use some JQuery to accomplish the event.

/* CMB2 Switch Event. Add the code below in a file named switch_metafield.js ------------- */
window.CMB2 = (function(window, document, $, undefined){
	'use strict';
	$(".cmb2-enable").click(function(){
        var parent = $(this).parents('.cmb2-switch');
        $('.cmb2-disable',parent).removeClass('selected');
        $(this).addClass('selected');        
    });
    $(".cmb2-disable").click(function(){
        var parent = $(this).parents('.cmb2-switch');
        $('.cmb2-enable',parent).removeClass('selected');
        $(this).addClass('selected');
    });
})(window, document, jQuery);

How to integrate CMB2 switch button in to a theme

To integrate the field in to a theme you must know "How to create custom meta boxes with CMB2"
If you know how to create custom meta boxes, then follow the codes below.

Add the following codes in you CMB2 main file.

/** START --- Initialize the CMB2 Metabox & Related Classes */
function initialize_showcase_meta_box() {
	require_once('switch_metafield.php'); //CMB2 Switch Field
}
add_action('init', 'initialize_showcase_meta_box', 9999 );

/** LOAD --- Related CSS and JS */
function load_custom_cmb2_script() {
	wp_enqueue_style( 'cmb2_switch-css', 'switch_metafield.css', false, '1.0.0' ); //CMB2 Switch Styling
	wp_enqueue_script( 'cmb2_switch-js', 'switch_metafield.js' , '', '1.0.0', true );  // CMB2 Switch Event
} 
add_action( 'admin_enqueue_scripts', 'load_custom_cmb2_script', 20 );

Now ready to use CMB2 switch button metafield

$cmb->add_field( array( 
	'name' => __( 'Field Name', 'cmb2' ),
	'desc'    => __( 'Field Description', 'cmb2' ),
	'id'      => 'your_switch_button',
	'type'    => 'switch',
	'default'    => 0,
	'label'    => array('on'=> 'Yes', 'off'=> 'No')
));
About This Author

My name is Parameshwar Roy (P. Roy), and I am a web developer. This is my personal blog to record my own thoughts. Though I am not a natural writer, I love to share my experiences. Hope my experiences will be useful to you...read more about me

Leave A Reply