• Blog

    Latest from our Blog

  • Tools

    Our Favourite WP Tools

  • Hosting

    Recommended Web Hosts

  • Coupons

    Get great money off deals

  • Themes

    WordPress Theme Directory

  • Plugins

    WordPress Plugins Directory

  • Promote

    Your WordPress Product

This is the third post in our WordPress CMS Features series. Previously we covered How to Create Custom Post Types and How to Create Custom Taxonomies. The purpose of these tutorials is to help WordPress powered website admins and users to understand how to use WordPress more efficiently as a powerful CMS.

One feature that any user would like to see in their CMS is the ability to modify the Writing Screens for their website users, authors and contributors. WordPress provides a handful of tools to do that. The simplest is to add Meta Boxes in your Post Edit screen. In today’s post we are going to learn how to create Meta Boxes, store data filled in the meta boxes, and reuse that data in content, templates, themes and website.

Preparation

Some not-so expert level WordPress users, like myself, find Meta Boxes too complex. I learned that they are not so complex. So I will try to explain them in an easy step-by-step tutorial.

  • First we will create a meta box.
  • In the second step we will add that meta box into our custom post type for movie reviews.
  • We will add code to accept data entered through the meta box and process it.
  • We will add that data to meta information for our post.
  • We will use that data in our templates.

Creating Custom Meta Box

In the first step we are going to create a meta box where our writers, editors, reviewers can add IMDB URL for the movies they are reviewing. For those who just joined us from this post, we are using a custom post type in our series of tutorials, it is called movie_reviews. Please replace movie reviews with either post or any custom post type where you want to display the meta box.

Hint:This code goes into your theme’s functions.php file or in a functionality plugin.

/* We define two action hooks */
/* First one to add meta box */
/* Second one to do something with the data entered */

	add_action( 'add_meta_boxes', 'imdburl_add_custom_box' );
	add_action( 'save_post', 'imdburl_save_postdata' );

/* Now we will create a function imdb_add_custom_box we used in the action hook above */

function imdburl_add_custom_box() {

// inside the function we create our meta box using add_meta_box function

	add_meta_box(
		// an ID for the metabox

		'imdburl_sectionid',

		// title of edit screen visible to user
		__( 'IMDB URL', 'imdburl_textdomain' ),

		// Call Back Function which we will define in next step
		'imdburl_inner_custom_box',

		// custom post type you can set it to post or any registered custom post type
		'movie_reviews' ,

		// Show in side you can set it to advanced or normal
		'side',

		// priority level if you set it to high this box will be first in the side panels
		'core'
	);
}

Explanation of the code:
We created two action hooks, the first one creates meta boxes, and the second one stores information entered through those meta boxes. Each action hook has a name, first to define action it takes, and then the function it uses to take that action.

Inside the function imdb_url_add_custom_box we ran our add_meta_box function with these parameters. The first one provides it an ID, then we provided it a title which will be visible on screen to the users. Then we provided a callback function which we will create in the next step. After that we defined that the meta box should only appear on posts inside Movie Reviews custom post type you can remove it and use post instead. Side and Core parameters define location of meta box in the Write Panel.

Adding Custom Meta Box to Post or Custom Post Type

We have created a Meta Box but it still does not appear in our post edit screen. In the second step we will add custom meta box to our custom post type movie reviews.

function imdburl_inner_custom_box( $post ) {

	// Use nonce for verification
	wp_nonce_field( plugin_basename( __FILE__ ), 'imdburl_noncename' );

	// The actual fields for data entry
	echo '<label for="imdburl_new_field">';
 _e("IMDB URL", 'imdburl_textdomain' );
 echo '</label> ';

	echo '<input id="imdburl_new_field" type="text" name="imdburl_new_field" value="$mydata" size="25" />';
}

The code above draws the custom meta box in the post edit area. However this box does nothing when data is entered into it.

Storing Custom Meta Box Data

Before storing the data entered into custom meta box, we want to make sure that it is not an autosave, then we want to confirm that the store request originates from our edit screen, and that the user editing has privileges to do so.

function imdburl_save_postdata( $post_id ) {
	// verify if this is an auto save routine.
	// If it is autosave then our form has not been submitted yet, so we dont want to do anything

	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
		return;
  	// verify this came from the our screen and with proper authorization,

	if ( !wp_verify_nonce( $_POST['imdburl_noncename'], plugin_basename( __FILE__ ) ) )
      		return;

	// Check user permissions

	if ( 'page' == $_POST['post_type'] )
  		{
	if ( !current_user_can( 'edit_page', $post_id ) )
        		return;
  		}
 	else
  	{
 	if ( !current_user_can( 'edit_post', $post_id ) )
        		return;
  	}
	// OK, we're authenticated: we need to find and save the data

	$mydata = $_POST['imdburl_new_field'];

So now we have data entered into meta box stored in $mydata variable. In the next step we are going to use Custom Fields to add the meta data into our post.

	add_post_meta($post_id, imdburl_new_field, $mydata, true);
	}

You may ask that why not just add custom fields manually? Well, Custom Fields interface does not remind your user that there is an entry they need to fill to make a good post. Using Custom Meta Boxes to collect data enables us to provide a good interface where users can quickly fill in the required information. This ensures consistency and similarity in the content created by multiple authors and users.

Complete Code

	add_action( 'add_meta_boxes', 'imdburl_add_custom_box' );
	add_action( 'save_post', 'imdburl_save_postdata' );

function imdburl_add_custom_box() {

	add_meta_box(
		'imdburl_sectionid',
		__( 'IMDB URL', 'imdburl_textdomain' ),
		'imdburl_inner_custom_box',
		'movie_reviews' ,
		'side',
		'core'
	);
}

function imdburl_inner_custom_box( $post ) {

	wp_nonce_field( plugin_basename( __FILE__ ), 'imdburl_noncename' );

	echo '<label for="imdburl_new_field">';
 _e("IMDB URL", 'imdburl_textdomain' );
 echo '</label> ';

	echo '<input id="imdburl_new_field" type="text" name="imdburl_new_field" value="$mydata" size="25" />';
}

function imdburl_save_postdata( $post_id ) {

	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
		return;

	if ( !wp_verify_nonce( $_POST['imdburl_noncename'], plugin_basename( __FILE__ ) ) )
      		return;

	if ( 'page' == $_POST['post_type'] )
  		{
	if ( !current_user_can( 'edit_page', $post_id ) )
        		return;
  		}
 	else
  	{
 	if ( !current_user_can( 'edit_post', $post_id ) )
        		return;
  	}

	$mydata = $_POST['imdburl_new_field'];

	add_post_meta($post_id, imdburl_new_field, $mydata, true);

	}

Using Meta Data into your Templates

To display this meta data, add this code into your templates where you want to display meta data.

<!--?php  	$imdb_url = get_post_meta($post--->ID, 'imdburl_new_field', true);
	echo "<strong>IMDB URL</strong>:'.$imdb_url.'";
?>

We have used get_post_meta function, provided the post and the meta key for the custom field to look for. The last parameter is set to true to fetch this meta information as a single string.

Conclusion

Custom Meta Boxes allow you to create rich UIs for your edit screen. This enables authors or contributors on your site to provide information you need for each entry. This powerful feature is very useful in creating highly customized WordPress websites. In the coming posts we will be discussing more powerful CMS features of WordPress and how to enable and use those features, so if you liked this post you might want to subscribe or follow us on twitter.


Noumaan is a blogger and social media expert. He loves Quora, Facebook, Wordpress, OpenSource Software and The Sims.

Leave Yours +

6 Comments

  1. I have read your previous posts too,They help me quite lot. This post also seems to be quite useful. Thanks for sharing. Looking for further useful posts.

  2. Great article, that first screenshot and subsequent code gave me a really good idea on how I can reformat the back end of my site.

  3. The value don’t show on update, just the $mydata (screenshot http://cl.ly/JwTn). I just copy all your code and change to my post type name. Can you help me out?

  4. Hello
    If I wanted to change the value as I do?
    The tutorial is missing the function to change

    Hello and thank you

  • Comments are Closed

Search

Our Sponsors