How To Create CMB2 Image_Select Field Type

  • Update On March 29th, 2017
  • in WordPress
CMB2 Image select Field Type 800x249 - How To Create CMB2 Image_Select Field Type

This post was last updated on March 29th, 2017 at 04:21 pm

Extending CMB2 field types is very easy with CMB2's custom (Custom Metaboxes and Fields for WordPress) field type option. In this article, I will share how to create an Image_select field type.

Let's Create CMB2 Image_select Field Type

just like my previous tutorial, Image_select field is also very simple to build using CMB2's field creation methods. Start by defining the field markup, you need to hook into the ‘cmb2_render_{field-type}’ action. So, our action to hook into is 'cmb2_render_image_select'.


/* CMB2 image_select Field. Add the code below in a file named image_select_metafield.php ------------- */
function cmb2_render_image_select( $field, $escaped_value, $object_id, $object_type, $field_type_object ) {
$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']).'"':'');
$default_value = $field->args['attributes']['default'];
$image_select = '<ul id="cmb2-image-select'.$field->args['_id'].'" class="cmb2-image-select-list">';
foreach ( $field->options() as $value => $item ) {
$selected = ($value === ($escaped_value==''?$default_value:$escaped_value )) ? 'checked="checked"' : '';

$image_select .= '<li class="cmb2-image-select '.($selected!= ''?'cmb2-image-select-selected':'').'"><label for="' . $field->args['_id'] . esc_attr( $value ) . '"><input '.$conditional_value.$conditional_id.' type="radio" id="'. $field->args['_id'] . esc_attr( $value ) . '" name="' . $field->args['_name'] . '" value="' . esc_attr( $value ) . '" ' . $selected . ' class="cmb2-option"><img class="" style=" width: auto; " alt="' . $item['alt'] . '" src="' . $item['img'] . '"><br><span>' . esc_html( $item['title'] ) . '</span></label></li>';
}
$image_select .= '</ul>';
$image_select .= $field_type_object->_desc( true );
echo $image_select;
}add_action( 'cmb2_render_image_select', 'cmb2_render_image_select', 10, 5 );

Styling The Image_select Field

Now we will style the field to look like a button set.

/* CMB2 Image_select Field Styling. Add the code below in a file named image_select_metafield.css ------------- */
.cmb-row.cmb-type-image-select .cmb2-image-select-list{margin: 0 !important; }
.cmb-row.cmb-type-image-select .cmb2-image-select-list .cmb2-image-select input[type="radio"] { display: none; }
.cmb-row.cmb-type-image-select .cmb2-image-select-list .cmb2-image-select{ display: inline-block; margin: 0 10px 3px; min-width: 80px; padding: 2px 15px 2px 0; text-align: center; }
.cmb-row.cmb-type-image-select .cmb2-image-select-list .cmb2-image-select:first-child{margin-left:0} 
.cmb-row.cmb-type-image-select .cmb2-image-select-list .cmb2-image-select img { border: 4px solid #F1F1F1; }
.cmb-row.cmb-type-image-select .cmb2-image-select-list .cmb2-image-select.cmb2-image-select-selected img { border-color: #005077; }

Enabling the event for the CMB2 Image_select Field

Now we need to use JavaScript to enable image click event, using JQuery.

/* CMB2 Image_select Event. Add the code below in a file named image_select_metafield.js ------------- */
window.CMB2 = (function(window, document, $, undefined){
    'use strict';
    $('ul.cmb2-image-select-list li input[type="radio"]').click(
	function(e) {
	    e.stopPropagation(); // stop the click from bubbling
	    $(this).closest('ul').find('.cmb2-image-select-selected').removeClass('cmb2-image-select-selected');
	    $(this).parent().closest('li').addClass('cmb2-image-select-selected');
	});
})(window, document, jQuery);

Lets Find How we can integrate CMB2 Image_select field 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 metafields main file.

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

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

Now we are ready to use CMB2 Image_select Field. For example:

$cmb->add_field( array(    
    'name' => __('Image Select', 'cmb2'),
    'desc' => __('page layout using image select', 'cmb2'),
    'id'   => $prefix . 'page_custom_layout',
    'type' => 'image_select',
    'options' => array(
        'disabled' => array('title' => 'Full Width', 'alt' => 'Full Width', 'img' => $image_path . 'img/sidebar-disabled.gif'),
        'sidebar-left' => array('title' => 'Sidebar Left', 'alt' => 'Sidebar Left', 'img' => $image_path . 'img/sidebar-left.gif'),
        'sidebar-right' => array('title' => 'Sidebar Right', 'alt' => 'Sidebar Right', 'img' => $image_path . 'img/sidebar-right.gif'),
        'sidebar-leftright' => array('title' => 'Both Sidebars', 'alt' => 'Both Sidebars', 'img' => $image_path . 'img/sidebar-both.gif'),
    ),
    'default' => 'default',    
));
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

4 Comments

You can post comments in this post.


  • Really nice tutorial. I’ll certainly give it a try. Thanks for sharing!

    Adriano Monecchi 8 years ago Reply


  • Very nice. One thing though: the way you wrote it you can only use it once in a CMB2 form. In order to re-use it on several occasions you’d need to rethink and rewrite a few things.

    The main thing that makes this a bigger task is that you’re doing the selection via radio inputs that aren’t displayed.

    Anyway, thanks for your work – it got me started doing my own.

    Bernhard 8 years ago Reply


    • Parameshwar Roy Proy 150x150 - How To Create CMB2 Image_Select Field Type

      Thanks for your comment. I’ve made some adjustment, it should work fine. Let me know if you can’t re-use it.

      P. Roy 8 years ago Reply


      • Notice: Undefined index: default in /opt/lampp/htdocs/wordpress/test/wp-content/themes/drubo/inc/plugins/cmb2img/image_select_metafield.php on line 6

        mamun 7 years ago Reply


Leave A Reply