Themergency fooplugins.com

Add Metaboxes To Your Plugins With CMB

| 0 comments

This is day 4 of my WordPress Developer Advent Calendar.

When writing more complex plugins for WordPress, you usually end up registering a few custom post types. And then the next logical step is to add fields to these post types. And this means you need to add metaboxes to your post types.

On November 27th, Custom Metaboxes and Fields v1.0.0 was released. CMB makes it really simple to include complex metaboxes in your plugins with little effort. So I took it for a spin to see just how easy it was to include in a plugin. Not even 5 minutes later, I had a glorious new metabox when adding a page in the WP backend:

This is what I did:

    1. I created a new single-file plugin called “Custom Metaboxes And Fields Showcase”
    2. I pulled down the latest CMB code (as a submodule) into a directory called “includes/metabox”:
      git submodule add https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress.git includes/metabox/
    3. I do a check for admin and hook into the init action:
      if (is_admin()) {
      	add_action( 'init', 'cmb_showcase_load_metabox' );
      }
    4. I include the CMB example file and the CMB init.php file (note that the init.php must be included AFTERWARDS):
      function cmb_showcase_load_metabox() {
      	require_once( 'includes/metabox/example-functions.php' );
      	require_once( 'includes/metabox/init.php' );
      }
    5. Thats it!

Example plugin on Github

I posted the example plugin on Github. Download it and play around locally to see how easy it actually is. See my note above that the example-functions.php file must be includes after the init.php file. This is because the example functions file hooks into the cmb_meta_boxes action and that is fired from the init.php file, so if you included it after init.php then nothing would happen! This happened to me at first so please take note!

Adding your own metaboxes

CMB comes with dozens of field types including datepickers, colour pickers and WYSIWYGs. You also add metaboxes by simply creating an array that CMB understands. From their documentation:

<?php function be_sample_metaboxes( $meta_boxes ) { 	$prefix = '_cmb_'; // Prefix for all fields 	$meta_boxes[] = array( 		'id' => 'test_metabox',
		'title' => 'Test Metabox',
		'pages' => array('page'), // post type
		'context' => 'normal',
		'priority' => 'high',
		'show_names' => true, // Show field names on the left
		'fields' => array(
			array(
				'name' => 'Test Text',
				'desc' => 'field description (optional)',
				'id' => $prefix . 'test_text',
				'type' => 'text'
			),
		),
	);
	return $meta_boxes;
}
add_filter( 'cmb_meta_boxes', 'be_sample_metaboxes' );