Beginner's Guide for WordPress - Start your WordPress Blog in minutes.
Choosing the Best
WordPress Hosting
How to Easily
Install WordPress
Recommended
WordPress Plugins
View all Guides

How to Add Custom Meta Boxes in WordPress Posts and Post Types

Last updated on by
Follow WPBeginner on YouTube
How to Add Custom Meta Boxes in WordPress Posts and Post Types

Just last week, we showed you how to add custom meta fields to custom taxonomies in WordPress. That article brought our attention to another important topic of how to add custom meta boxes in WordPress posts and post types. We wrote about a plugin method of adding meta boxes and custom write panels using More Fields plugin, but the development of that plugin has stopped. We had linked to some good tutorials that showed how to do add custom meta boxes in WordPress from our Custom Fields 101 article however all those are no longer available. Therefore in this article, we will show you how to add custom meta boxes in WordPress posts and custom post types.

Note: This tutorial is for designers and developers.

Because the goal of this article is to show you how to create reusable meta boxes in WordPress, we will be utilizing a Custom Metaboxes and Fields for WordPress class (CMB) by Andrew Norcross (@norcross), Jared Atchison (@jaredatch), and Bill Erickson (@billerickson). All three of these guys are very well reputed in the WordPress community. They combined their efforts to create a powerful solution to make their job and other’s jobs a lot easier.

First thing you need to do is download the CMB class. Create a new folder and call it “custom-meta-boxes-wp”. Extract the CMB zip files in here.

Now let’s create a blank PHP file, and call it cmb-wp.php. This is the file that we will use to define our plugin and create all the meta boxes that we need. Below is an example content that you can place in this file:

<?php
/*
Plugin Name: Sitename Custom Meta Boxes
Plugin URI: http://www.wpbeginner.com/
Description: Create Meta Boxes for Sitename.
Version: 0.1
Author: Syed Balkhi
Author URI: http://www.wpbeginner.com/
License: GPL v2 or higher
License URI: License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/

//Initialize the metabox class

function wpb_initialize_cmb_meta_boxes() {
	if ( ! class_exists( 'cmb_Meta_Box' ) )
		require_once(plugin_dir_path( __FILE__ ) . 'init.php');
}

add_action( 'init', 'wpb_initialize_cmb_meta_boxes', 9999 );

//Add Meta Boxes

function wpb_sample_metaboxes( $meta_boxes ) {
	$prefix = '_wpb_'; // 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', 'wpb_sample_metaboxes' );

The above example is very basic. It just adds a sample test meta box with a text field on “pages”. As you can see, that you have the option to customize the post type, and just about everything. CMB class supports the following field types:

  • text
  • text small
  • text medium
  • text money
  • date picker
  • date picker (unix timestamp)
  • date time picker combo (unix timestamp)
  • time picker
  • color picker
  • textarea
  • textarea small
  • textarea code
  • select
  • radio
  • radio inline
  • taxonomy radio
  • taxonomy select
  • checkbox
  • multicheck
  • WYSIWYG/TinyMCE
  • Image/file upload

Here is the wiki page that will show you how to add all the field types. There is also an example-functions.php file that you can use to reference.

Once you are done, upload the folder in your plugins folder. Now, you can easily display these fields in your loop by using get_post_meta() function. Here is a tutorial if you want to display custom fields outside the loop.

Ever since we found this CMB class, we have not looked back. We use this on all of our projects and client projects as well. If you are a designer/developer, then you will find this to be really easy and help you improve your workflow. We hope that this tutorial has helped you add custom meta boxes in WordPress posts and post types.


Editorial Staff at WPBeginner is a team of WordPress lovers led by Syed Balkhi. Page maintained by Syed Balkhi.

WPBeginner's Video Icon
Our HD-Quality tutorial videos for WordPress Beginners will teach you how to use WordPress to create and manage your own website in about an hour. Get started now »
  • Mário Vital

    the same problem with me !

  • Rajneesh

    Hi

    Everything is working fine for me only one issue with show custom filed data in front end.

    Warning: Missing argument 1 for get_post_meta()
    defined in wp-includes/post.php on line 1769

    Any suggestion please.

    Thanks

  • Hash Varsani

    Hi,

    I’ve got this installed and working fine so far. Just wondering how to add field types for URL and email if they are not listed in he supported list.

  • Sergey

    Thanks for the post.
    But I can’t understand – where shold all these files (class + cmb_wp) should be located?

  • Daniele

    hi,

    i followed the tutorial but after uploaded folder, i can’t see anything… where am i wrong?

    • http://www.wpbeginner.com Editorial Staff

      Daniele,

      If you follow the instructions word for word, then you will have a metabox under pages with a sample text field.

  • Victoria

    I’m having a similar problem as Errol, I lose all data once I click the update or publish button and nothing comes up when I get post meta. I had this happen in a theme before but in that case it be visible on the site but magically migrate to the custom fields section once it was published. I can’t find this data ANYWHERE… Could it be the “_wpb_” prefix being used? I noticed the example functions do not have that.

    I’m no wizard at this stuff but I’ve tried deactivating the plugins, and re-installing THIS plugin with no avail. Any help would be appreciated!!! Thanks.

    • Jeffrey Samorano

      To Victoria and Errol, I was having the same problem and had to make sure that the IDs had no spaces. I don’t know if this applies to your individual situation but it worked for me.. My situation was that *some* were saving and some were not. I noticed the ones that were not saving had spaces in the array ID (‘id’ => ‘id-name’)… Hope this helps!

  • Мах

    How to use this class for add the castom metaboxes to the category?

  • Dorijan

    I was wondering if it was possible to specify which metaboxes to display at which page (I have multiple but need only certain metaboxes on certain template pages)?

  • VegasKev

    For some reason when using this script all line breaks are lost when the data is stored in the db tables so if you have a custom post meta that is for a description (like I do), you cannot enter multiple paragraphs, as they line breaks for those paragraphs will not be displayed in your custom post type’s post template, since they are lost during the save process.

    Does anyone have a fix for this? I really need to be able to have multiple paragraphs in a few of my fields and I’m not sure how to modify the code to accept the line breaks entered into the field when it is saved.

    Any guidance would be greatly appreciated. Thanks in advance.

    • http://www.wpbeginner.com Editorial Staff

      Use a wysiwyg field and see if the issue is the same. You can have line breaks if you use HTML paragraph tag or line break tags.

      • VegasKev

        Thanks for the tip. I didn’t even think of that. I wonder if a normal carriage return will automatically create a line break as it does if you do a carriage return in the WP post editor?

  • The Cableguy

    Man I simply can not get my custom fields to display in my theme at all. This is friggen nutz~!

    • VegasKev

      Have you registered your custom post type and created your custom post template yet?

      http://codex.wordpress.org/Post_Types

      http://codex.wordpress.org/Post_Type_Templates

      If not, start with those and then knock out your metabox & custom post meta work, then add your custom post meta ids from your metaboxes for your custom post type to be displayed in your custom post template and you will be all good.

      • The Cableguy

        Oh, ok… I simply thought that all I had to do was create the plugin and then simply use something like
        ID, $key, true); ?> and simply change “mykey” to the key value I made and change “key” to the same thing to make my custom fields display in my single.php file, lol. I did not know I had to create other files and all.
        The custom fields do show up in my post editor, oh well, I guess its time to get reading, lol.

      • The Cableguy

        Oh, ok… I simply thought that all I had to do was create the plugin and then simply use something like
        ID, $key, true); ? > and simply change “mykey” to the key value I made and change “key” to the same thing to make my custom fields display in my single.php file or my salesposts.php , lol. I did not know I had to create other files and post types and register stuff for it to work, lol. .
        The custom fields do show up in my post editor, just cant get them to display in my posts, oh well, I guess its time to get reading, lol.

        • VegasKev

          No problem. If you need help with custom post types and post templates, let me know, they’re fairly easy once you get the hang of them.

  • Kev

    Here’s the pastebin…sorry…was lazy…you can edit my comments to minimize clutter if you want.

    http://pastebin.com/2AsS59yJ

    Again, I appreciate any guidance.

    • http://www.wpbeginner.com Editorial Staff

      Is this a custom WP query? Try using get_the_id instead of $post->ID. See if that works for you.

  • Alvin

    I would like to use reusable profile fields for my buddypress site.
    Users can show their “interests” within their profile by adding a new textfield , now i want to add as many as they need (max 10)
    Is this possible ? I dont have a clue on where to start , help ?

  • J A McRae

    Many thanks for the info. It works; I would like to learn some more :)

    1) Where is a good place to learn more about Classes. I’d like to understand a little better what it is I’m applying here. Not an easy term to google

    2) What if I want to use this code in my themes as opposed to a plugin? Where could I put this folder, if i put the code portion in my functions file?

    JA

  • Toni Michel

    Hi there! I am trying to follow this tutorial to creat a subtitle field in my custom post_type team.

    http://wordpress.stackexchange.com/questions/88959/add-additional-field-to-custom-post-type

    I think i’m doing the same you are in here but it seems that the field doesn’t show up in the wp-admin when adding a new team post

    • http://www.wpbeginner.com Editorial Staff

      Can you send the pages field in an array like we are doing. Just to see if that fixes the problem.

      • Toni Michel

        Hi there, thanks for your reply!

        I changed to:

        ‘pages’ => array(‘team’)

        But it gives me the same result. No errors but the field is not added.. any idea (the post_type team works)?

  • Oliver

    Great work. just one question: does it work for custom post types? how would I define it?

    • http://www.wpbeginner.com Editorial Staff

      Yes it does. In line 30 of the code, define your custom post type in an array. Like we have page. You can have page, post. You can have page, post, books, movies, recipes….

      • Oliver

        Excellent. Thank you!

  • Errol

    I have followed this word for word – as it stands I get just about everything to show up as it should.
    However when I publish the page I seem to loose all the content (data) which I have placed into the field, seems like it is not saving to the db?

    HELP!

    Thanks
    E!

    • http://www.wpbeginner.com Editorial Staff

      That’s weird. If you are using the class, then it shouldn’t happen. Could be a conflict with another plugin. Can you try deactivating all plugins and see if the class works by itself.

  • Praveen

    Please could you help how to show meta box in posts instead of pages.

    I changed this line ‘pages’ => array(‘page’), // post type
    to
    ‘pages’ => array(‘posts’), // post type
    ‘pages’ => array(‘post’), // post type
    ‘posts’ => array(‘post’), // post type

    but of no use. please help…

    • http://www.wpbeginner.com Editorial Staff

      This is how we are using it on WPBeginner, and it works fine:

      'pages'      => array( 'post', ), // Post type
      • Praveen

        Thanks a lot. I figured it out. Actually i have been editing local copy of the plugin and expecting it to work. This tutorial is awesome. It helped me a lot.

        My website is a deals website and i am searching for custom fields from long time so that i can add expiry time, mrp and discount price etc. Finally i implemented this on my site.

  • DZ.Slick

    Nice tut here. Just wanted to know if I’m allowed to develop this into a different kind of plugin.
    Thanks

    • http://www.wpbeginner.com Editorial Staff

      It is open source. You can use it however you please.

      • Julien Maury

        Great ! Pretty good stuffs to make our plugins ! Thanks a lot

  • vajrasar

    Great Post!
    I used it to make Custom Meta Box as Cast, Genre, Director and Show Timings. I followed the instruction. Downloaded everything to plugins directory (activated the plugin) made the php file, used your code and altered it to make my desired field.
    Even, the boxes successfully showed up below all posts (i changed post type to Posts instead of Pages). But the real problem is how can I show it on front end?
    I used get_post() and also visited everything possible on net in past 3 hours, but no success. If you can point out anything. Thanks.

    • http://www.wpbeginner.com Editorial Staff

      You have to use get_post_meta function.

      • Vajrasar

        Yea got it working, was using duplicate field names [Bill Erickson helped to point it out]. Thank You for such an awesome piece on Custom MetaBoxes. Thumbs Up.

  • Mattia Frigeri

    Ok, seems interesting… thanks.
    But for us not so expert, you should explain where to put which file in which folder, inside our wordpress installation!

    • Dunners

      Totally agree, this all sounds very exciting and just what I’m looking for but the post lacks major detail about implementing this. Also the code of the example-functions.php seems to totally knock out my blog!

      Any chance that this post can be fleshed out?

      • http://www.wpbeginner.com Editorial Staff

        If you read the note in the post, it clearly says that this post is for designers and developers. There are certain things that cannot be broken down further without making it insanely long and boring. Which part are you stuck with in the tutorial? Here is a simple step by step:

        1. Download the Zip and Extract it
        2. Upload the folder into your wp-content/plugins/ as a new plugin.
        3. You should see a new plugin showing up in your admin panel. Activate it.
        4. Use the reference wiki to add meta fields as you please.

  • Jukka Hotokka

    Thank you! This is very helpful article.