For a more recent walkthrough of custom metaboxes, see my Custom Metaboxes presentation from June 2018. The post below was written in 2011 and its information is out of date.
When using WordPress as a CMS, you’ll often need to associate data with a post or page that doesn’t fit the predefined inputs (title, post editor, categories…). WordPress has a built-in feature called “Custom Fields” for managing this data, but the interface isn’t user-friendly.
Custom Meta Boxes allow you to build clean, understandable interfaces for entering metadata. I use them on almost every project. Above is a screenshot of my CRM which makes extensive use of metaboxes (full screenshot).
You could use a plugin like More Fields to create them, but I prefer to have them included in the theme rather than dependent on a plugin.
Here’s how to set up your own meta boxes:
- Download a copy of our metabox code from GitHub
- Create a “lib” directory in your theme or child theme, and a “metabox” directory inside “lib”. Upload the files you downloaded above into /wp-content/themes/your-theme/lib/metabox
- Include /lib/metabox/init.php in your functions.php file, and define your metaboxes in an array (see below).
Here’s an example of using the metabox code to create a Rotator Options metabox that’s displayed on the Rotator post type. This is what I use when installing the WP Rotator plugin.
Each meta box is stored as an array. There’s a ton of field options, including text, textarea, checkbox, dropdown list, and WYSIWYG. For examples on how to use all the fields, look at /metabox/example-functions.php.