Randy Hoyt

Add Custom Meta Boxes to Your Plugin

Earlier this year, Bill Erickson announced a new library called Custom Meta Boxes that provides an easy way for developers to add pre-defined custom fields to WordPress content. I have used a number of plugins to achieve this in the past, and at the time of Bill’s announcement I was writing my own similar library. I have since used the Custom Meta Boxes library on a handful of sites, and I plan to use it going forward. I have already contributed one patch to the project, and I plan to start contributing to it more.

The included documentation demonstrates how to add the library to your theme. I have long believed code like this belongs in a custom functionality plugin instead of in a theme (check out a recent blog post on WP Candy), plus the library is a great tool for developers to include in their plugins. Here are instructions for using this library in your plugin.

  1. Download a copy of the library:
    Custom-Metaboxes-and-Fields-for-WordPress (GitHub)

  2. Create a folder within your plugin (I usually call mine “metaboxes”) and place the contents of the library within that folder.

  3. Add an action on WordPress’s init hook that includes the init.php file from the library. I specify a very large number for the priority so that including this library is the last thing WordPress does as part of initializing itself. (Check first if the class exists to avoid conflicts with other plugins or a theme that has already included a different copy of the library.)

    add_action('init','rrh_init_cmb_meta_boxes',10000);
    function rrh_init_cmb_meta_boxes() {
    	if (!class_exists('cmb_Meta_Box')) { require_once('metaboxes/init.php'); }
    }
  4. Add a filter to the library’s cmb_meta_boxes hook that defines your custom meta boxes.

    add_filter('cmb_meta_boxes', 'rrh_assignment_meta_boxes');
    function rrh_assignment_meta_boxes($meta_boxes) {
    	$meta_boxes[] = array(
    		'id' => 'rrh_assignment_data',
    
    		...
    
    	);
    	return $meta_boxes;
    }

For more information about this library and documentation on setting up custom meta boxes, check out the library’s example-functions.php file on GitHub.

Download

This article builds upon my talk at edUi 2011 on how to set up custom post types. You can view that presentation and download the necessary code to make all this work on the page for that presentation: “Advanced WordPress Features & Customizations.”