From the beginning of WordPress, custom fields have been used in different versions of WP, but then they added metabox support in version 2.5, where users can add extra data to any post or page. Because you (as a developer or advanced user) can add unlimited number of data fields, it’s a very handy feature. Imagine having a real estate listing as a post in WP. There is a requirement to add all the info about a property – adding metaboxes for property size, year, image, and location is the ideal solution! You don’t have to fiddle in adding these time-consuming details in as part of post body and then styling them with CSS.
Adding Your Own Custom Fields
It’s possible to develop and add your own custom fields, the documentation is available on the official WordPress documentation website. Here you will also find a number of other tutorials.
But using a plugin is way easier and faster. Some plugins give you a possibility to add custom meta boxes via admin UI.
- If you are a developer and don’t want to have extra widgets or settings floating around in the dashboard then I recommend using CMB2 plugin. I’ve used this framework for 2-3 years and it’s been very reliable, very well documented and easy to use.
CMB2 plugin adds metabox framework, which you can extend in your own plugin or theme. I recommend creating your own plugin, require CMB2 plugin as a dependency and just add all necessary metaboxes. Below you will find step-by-step directions.
Step 1. Install CMB2 plugin and activate it.
Step 2. Create new folder inside wp-content/plugins. For example ndm-plugin and then create index.php inside this folder.
Insert this code (change meta info to your name), this initiates new plugin and requires CMB2 to be installed and active.
Step 3. Create post-metabox.php file inside your new plugin folder and add all your metaboxes there. (sample code which you can copy and change is inside wp-content/cmb2/example-metaboxes.php).
Step 4. Create as many files inside your plugin folder as you want, for example you can add metaboxes for pages (or specific page), so your file name would be home-metaboxes.php pages-metaboxes.php and then require this file(s) in your index.php.
This is just simple introduction how to easily and quickly add metaboxes to your theme and keep them around even when you change your theme in the future.