Ever tried to build metaboxes in WordPress? It's a mess, not only for beginners but even for advanced WordPress developers. Luckily for the WordPress community, the community itself can come up with elegant solutions for these kinds of messy problems. CMB2 is one of them.
In this part of the "Toolbox of the Smart WordPress Developer" series, we're going to go through CMB2, an extensive library for developing custom metaboxes and forms in WordPress.
The Extremely Unexceptional Way to Create Custom Metaboxes
Since this isn't a tutorial about creating custom metaboxes, I'm not going to teach you how to do it by using core functionality—but I'll give out a couple of useful links. Instead, I'm going to go over the mundane routine of it:
Creating the metabox: Admittedly, this part's essential and even CMB2 uses a similar way of doing it—you have to create the custom metabox using the add_meta_box()
function... within a function that hooks to the add_meta_boxes
action. Not too easy, not too hard, but in between the two.
Create the fields to display in the metabox: In this part, you have to create a separate function (that you also have to refer to in the add_meta_box()
function) and write vanilla HTML in it, like div
s and label
s and input
s, in order to display your form fields, which won't work unless you bind the HTML with complicated PHP. Text inputs are fine, but creating dropdowns or checkboxes? Prepare to get confused. (Don't even get me started on file uploads and color pickers.) Oh, you forgot to use wp_nonce_field()
for security? Too bad, your code will never work.
Sanitize and save the field values: Yeah. In order to make the form store the data, you have to use yet another function to check a bunch of things, sanitize the data and save the values in your custom metabox. And you have to hook that function to the save_post
action. Neat.
If you want to do it "the core way" and spend hours on creating a couple of metaboxes, well, good for you, taking the high road. But of course, there might come a time that you just won't be able to use helper frameworks like CMB2. In that case, you can refer to this SitePoint tutorial by Narayan Prusty or this extensive series of tutorials by Tom McFarlin on Tuts+ Code.
Enter CMB2: The Exceptionally Awesome Way to Create Custom Metaboxes
And what if I told you that you can create custom metaboxes by creating one function that hooks to one action, and using very smart functions that do all the hard work of creating the HTML and magically binding everything together? And believe me, I'm not exaggerating even a tiny bit!
With the help of CMB2, you will be able to create custom metaboxes in a fraction of the time you would spend on doing it "the core way".
Setting Up CMB2
CMB2 comes in two forms: in the plugin form and in the framework form. If you're going to use CMB2 in projects that aren't going to be released for a community, I suggest that you use the plugin, because updating the CMB2 plugin would be much easier, and you won't have to include the files of the CMB2 engine. But if you're going to release your project to a community, you'd better integrate CMB2 into the project by downloading the files from GitHub, placing them into your project's folder, and using the lines below in it:
<?php // require the init.php file if ( file_exists( __DIR__ . '/path/to/cmb2/init.php' ) ) { require_once __DIR__ . '/path/to/cmb2/init.php'; } ?>
Of course, keep in mind that you have to edit the lines above to point to CMB2's init.php
file.
Creating Your First Custom Metabox
Before creating our first metabox, we need to create our only function that will hook to CMB2's own cmb2_init
action:
<?php // hook the function to the cmb2_init action add_action( 'cmb2_init', 'cmb2_sample_metaboxes' ); // create the function that creates metaboxes and populates them with fields function cmb2_sample_metaboxes() { // set the prefix (start with an underscore to hide it from the custom fields list $prefix = '_my_prefix_'; } ?>
After that, creating the metabox is as easy as creating a new variable:
<?php // hook the function to the cmb2_init action add_action( 'cmb2_init', 'cmb2_sample_metaboxes' ); // create the function that creates metaboxes and populates them with fields function cmb2_sample_metaboxes() { // set the prefix (start with an underscore to hide it from the custom fields list $prefix = '_my_prefix_'; // create the metabox $cmb = new_cmb2_box( array( 'id' => 'test_metabox', 'title' => 'Test Metabox', 'object_types' => array( 'page', 'post', 'customposttype' ), // post type 'context' => 'normal', // 'normal', 'advanced' or 'side' 'priority' => 'high', // 'high', 'core', 'default' or 'low' 'show_names' => true, // show field names on the left 'cmb_styles' => false, // false to disable the CMB stylesheet 'closed' => true, // keep the metabox closed by default ) ); } ?>
Populating Your Custom Metabox With Fields
After creating our first custom metabox, it's time to make it useful by populating it with "fields" that CMB2 provides. And doing so is as simple as running a function with the metabox variable we just created:
<?php // metabox title $cmb->add_field( array( 'name' => 'Test Title', 'desc' => 'This is a title description', 'type' => 'title', 'id' => 'wiki_test_title' ) ); // email input $cmb->add_field( array( 'name' => 'Test Text Email', 'id' => 'wiki_test_email', 'type' => 'text_email', ) ); // file uploader $cmb->add_field( array( 'name' => 'Test File', 'desc' => 'Upload an image or enter an URL.', 'id' => 'wiki_test_image', 'type' => 'file', // Optionally hide the text input for the url: 'options' => array( 'url' => false, ), ) ); // remember when I said doing a color picker would be super hard when using core functions? $cmb->add_field( array( 'name' => 'Test Color Picker', 'id' => 'wiki_test_colorpicker', 'type' => 'colorpicker', 'default' => '#ffffff', ) ); ?>
There are more than 30 field types provided by CMB2, including regular text inputs, WYSIWYG editors, date pickers, color pickers, file uploaders and even taxonomy selectors. For a full list of field types, check out this Wiki page of CMB2.
Even More Awesomeness
Creating fully functioning custom metaboxes is awesome as it is, but CMB2 doesn't stop there. There are a bunch of things that you can do with CMB2:
- You can use CMB2 to create an options page for your theme.
- You can make CMB2 work to create post submission forms.
- You can add your own
show_on
filters and conditionally show or hide your metaboxes. - And you can even create your own field types.
To learn more about CMB2's super powers like these, there are a few pages that you can check out:
- Third party resources for CMB2
- The "Tips & Tricks" page on the CMB2 Wiki
- CMB2 Snippet Library, a page that contains some very useful code snippets
- The blog of WebDevStudios, creators of CMB2
Wrapping Up for Today
There's no denying that sticking to the WordPress core while building stuff isn't always as simple as it sounds. So, using helper frameworks like CMB2 will speed up our development processes. And I believe that even though CMB2 is as awesome as it is now, it has way more room to improve (not just in the area of custom metaboxes, but also in other directions as well), so I'd keep an eye on this project if I were you.
See you in the next part where we'll go over WP-CLI, a one-of-a-kind WordPress tool that gives us the opportunity to manage our WordPress installations via the command line.
Comments