How to Add a Metabox to a Custom Post Type

metabox1Most custom post types in WordPress will need (or could benefit from) a unique set metaboxes for entering information.

For example, a “photography” post type might need fields for “location of photo”, “type of camera”, etc. And an “event” post type would probably need a “location” and an “event date”.

Metaboxes aren’t the easiest to set up- so I’ve written up this tutorial which shows how to add a one line field for “location” to an “event” post type.

Hopefully, you’ll be able to use this guide to add any sort of metaboxes you need.

Set Up the Post Type

If you are unfamiliar with how to set up custom post types, check out Justin Tadlock’s excellent tutorial. For this example, I am going to use a post type called “Event”, which goes in my functions.php file:

// Registers the new post type and taxonomy

function wpt_event_posttype() {
	register_post_type( 'events',
		array(
			'labels' => array(
				'name' => __( 'Events' ),
				'singular_name' => __( 'Event' ),
				'add_new' => __( 'Add New Event' ),
				'add_new_item' => __( 'Add New Event' ),
				'edit_item' => __( 'Edit Event' ),
				'new_item' => __( 'Add New Event' ),
				'view_item' => __( 'View Event' ),
				'search_items' => __( 'Search Event' ),
				'not_found' => __( 'No events found' ),
				'not_found_in_trash' => __( 'No events found in trash' )
			),
			'public' => true,
			'supports' => array( 'title', 'editor', 'thumbnail', 'comments' ),
			'capability_type' => 'post',
			'rewrite' => array("slug" => "events"), // Permalinks format
			'menu_position' => 5,
			'register_meta_box_cb' => 'add_events_metaboxes'
		)
	);
}

add_action( 'init', 'wpt_event_posttype' );

You may have your own custom post type set up completely different, but that’s fine. The important line of code for the metaboxes is ‘register_meta_box_cb’ => ‘add_events_metaboxes’- which calls the function to build the metaboxes.

You can rename the function to whatever you like, for instance ‘register_meta_box_cb’ => ‘add_photography_metaboxes’ might be better for a photography post type.

If the post type is being registered through a plugin or is one of the native post types, you can also use:

add_action( 'add_meta_boxes', 'add_events_metaboxes' );

Add Meta Box

The following code adds a metabox to the right side of the screen under the “Publish” box:

// Add the Events Meta Boxes

function add_events_metaboxes() {
	add_meta_box('wpt_events_location', 'Event Location', 'wpt_events_location', 'events', 'side', 'default');
}

You can read the full parameters for add_meta_box in the codex. I also listed them here:

<?php add_meta_box( $id, $title, $callback, $page, $context, $priority, $callback_args ); ?>

For the example above:

  • $id is “wpt_events_location”- or the html id that will be applied to this metabox.
  • $title is “Event Location”. This appears at the top of the new metabox when displayed.
  • $callback is the function “wpt_events_location” which will load the html into the metabox.
  • $page is “events”, the name of our custom post type.
  • $context is “side”. If you wanted it to load below the content area, you could put “normal”.
  • $priority controls where the metabox will display in relation to the other metaboxes. You can put “high”, “low” or “default”.

If you wanted to have two sets of metaboxes, perhaps one on the side and one below the content area, you could do something like this (Note: Don’t use this if you’re following the tutorial step by step, this is just an example of how it would be done):

// Add the Events Meta Boxes

function add_events_metaboxes() {
	add_meta_box('wpt_events_date', 'Event Date', 'wpt_events_date', 'events', 'side', 'default');
	add_meta_box('wpt_events_location', 'Event Location', 'wpt_events_location', 'events', 'normal', 'high');
}

You’d then have to make sure the two function wpt_events_date and wpt_events_location were defined to call the html code to go inside the metaboxes.

Generating the HTML for the Metabox

Continuing with the first example above, we’ll now have to generate the code that goes inside our “Event Location” metabox. To keep this as simple as possible, we’re just going to make one field:

// The Event Location Metabox

function wpt_events_location() {
	global $post;

	// Noncename needed to verify where the data originated
	echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' . 
	wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

	// Get the location data if its already been entered
	$location = get_post_meta($post->ID, '_location', true);

	// Echo out the field
	echo '<input type="text" name="_location" value="' . $location  . '" />';

}

At this point you should have a metabox showing up in your post. If you check your “events” post type, it should load on the right side like in the screenshot I posted. This will generate any html you choose, so, you could put as many input fields in here as you like, or html descriptions.

In order to class the inputs and descriptions correctly, check out the source code for other write panels in WordPress. See how they do textareas and select boxes. You can even add icons and generated text in these spots.

Saving

If you had tried to save your metabox data before this point, it just would have disappeared on the refresh because it wasn’t being saved. Here’s the code that updates the metabox when you click “Update” (adapted from Nathan Rice in the AgentPress theme):

// Save the Metabox Data

function wpt_save_events_meta($post_id, $post) {

	// verify this came from the our screen and with proper authorization,
	// because save_post can be triggered at other times
	if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
	return $post->ID;
	}

	// Is the user allowed to edit the post or page?
	if ( !current_user_can( 'edit_post', $post->ID ))
		return $post->ID;

	// OK, we're authenticated: we need to find and save the data
	// We'll put it into an array to make it easier to loop though.

	$events_meta['_location'] = $_POST['_location'];

	// Add values of $events_meta as custom fields

	foreach ($events_meta as $key => $value) { // Cycle through the $events_meta array!
		if( $post->post_type == 'revision' ) return; // Don't store custom data twice
		$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
		if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
			update_post_meta($post->ID, $key, $value);
		} else { // If the custom field doesn't have a value
			add_post_meta($post->ID, $key, $value);
		}
		if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
	}

}

add_action('save_post', 'wpt_save_events_meta', 1, 2); // save the custom fields

This code checks to make sure the user has privileges to update the post, then saves all the input data into the array $events_meta.

Source: http://wptheming.com/2010/08/custom-metabox-for-post-type/

Advertisements

3 thoughts on “How to Add a Metabox to a Custom Post Type

  1. This is a good read. Very clear comments. I have a question though, is it possible to use custom meta box for date and display it in archives group by date?

  2. Hi Pinaki, maybe you can help me by my Issue:

    I have created a Metabox in Woocommerce and if I select the 2nd value in my dropbox and fill out the other text field and save than nothing is saved.

    The Metabox works only the value is not saved.

    Thanks a lot

    Regards HyperV

    ‘/**
    * Display Metabox Shipment Tracking on order admin page
    **/

    add_action( ‘add_meta_boxes’, ‘BFM_add_meta_boxes’ );

    function BFM_add_meta_boxes(){

    add_meta_box(
    ‘woocommerce-order-my-custom’,
    __( ‘Paket verfolgen’ ),
    ‘order_my_custom’,
    ‘shop_order’,
    ‘side’,
    ‘default’
    );

    }
    function order_my_custom( $post ){
    $shipping = get_post_meta( $post->ID, ‘_BFM_shipping_tracking’, true );

    wp_nonce_field( ‘save_BFM_shipping’, ‘BFM_shipping_nonce’ );

    woocommerce_wp_select( array( ‘id’ => ‘BFM_shipping_service’, ‘label’ => __(‘Paketdienst: ‘, ‘woocommerce’), ‘options’ => array(
    ‘OPTION1’ => __(‘DHL’, ‘woocommerce’),
    ‘OPTION2’ => __(‘Hermes’, ‘woocommerce’)
    ) ) );
    woocommerce_wp_text_input( array( ‘id’ => ‘BFM_tracking_link’, ‘class’ => ”,’label’ => __(‘Verfolgungslink: ‘, ‘woocommerce’) ) );

    }

    /**
    * Save Shipping Tracking information
    **/
    function save_BFM_shipping( $post_id ) {

    // Check if nonce is set
    if ( ! isset( $_POST[‘BFM_shipping_nonce’] ) ) {
    return $post_id;
    }

    if ( ! wp_verify_nonce( $_POST[‘BFM_shipping_nonce’], ‘save_BFM_shipping’ ) ) {
    return $post_id;
    }

    // Check that the logged in user has permission to edit this post
    if ( ! current_user_can( ‘edit_post’ ) ) {
    return $post_id;
    }

    $shipping = sanitize_text_field( $_POST[‘BFM_shipping_service’] );
    update_post_meta( $post_id, ‘_BFM_shipping_tracking’, $shipping );
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s