3

Create A Simple Metabox For Custom Post Types

WordPress 3.0 has made creating custom meta boxes much more fun since you can completely alter the edit pages using them and make your own post pages entirely from metaboxes you've defined. Here's an example of how to create a URL and description metabox....
Create A Simple Metabox For Custom Post Types

Making a URL and Description Custom Metabox

Recently this topic was suggested as a new post idea for me to write about, so here I am writing about it. You can let me know of other ideas or topics you'd like to see a tutorial on here whenever you want, and if I am able to do it and have time I will surely do it.

So say you have a custom post type on your site, and as part of that post type, you want to allow for a way to enter in a URL and maybe a description or text of some sort for something related to the URL. This is not hard to do, it simply requires a couple of functions to do.

What Functions Are Needed

  1. We will need a function for displaying the metabox form fields, which will be used to save and update the data we enter into it.
  2. Then a function for processing the metabox form elements, in order to perform the actions of saving and updating the information.
  3. A function for adding the custom metabox function to WordPress via the 'init' action hook.
  4. Finally, we need a function to get and return the values of the fields for use within the theme on the frontend.

1. Displaying The Custom Metabox

First thing we need to do is create the metabox form fields. In doing that, we want to also check if there is any data saved in the post meta for the custom fields we are making, so we can output that into the input fields of the form.

Since we are making a URL input field, we should check to see if the URL entered is a valid URL using a regular expression. For this example I am just using a simple regex which will check to make sure the URL at least has the 'http://' at the beginning. If it does not, I output the message saying it's invalid, and add it to the input field.

/**
 * Display the metabox
 */
function url_custom_metabox() {
	global $post;
	$urllink = get_post_meta( $post->ID, 'urllink', true );
	$urldesc = get_post_meta( $post->ID, 'urldesc', true );
	
	if ( !preg_match( "/http(s?):\/\//", $urllink )) {
		$errors = 'Url not valid';
		$urllink = 'http://';
	} 
	
	// output invlid url message and add the http:// to the input field
	if( $errors ) { echo $errors; } ?>
	
	<p><label for="siteurl">Url:<br />
		<input id="siteurl" size="37" name="siteurl" value="<?php if( $urllink ) { echo $urllink; } ?>" /></label></p>
	<p><label for="urldesc">Description:<br />
		<textarea id="urldesc" name="urldesc" cols="45" rows="4"><?php if( $urldesc ) { echo $urldesc; } ?></textarea></label></p>
<?php
}

Notice how I am checking if the meta fields have a value and if they do, then echo it out within the input and textarea fields.

2. Processing the Metabox Form Fields

Next, we need to process this information when the form is submitted to save as a draft or publish the post. There are a number of ways to do this, but the simplest way to do it is just simply pass the $post_id to the function, and make $post global.

Then check if the $_POST variable is set, meaning has the form been submitted, and if so then update our post meta options using update_post_meta().

/**
 * Process the custom metabox fields
 */
function save_custom_url( $post_id ) {
	global $post;	
	
	if( $_POST ) {
		update_post_meta( $post->ID, 'urllink', $_POST['siteurl'] );
		update_post_meta( $post->ID, 'urldesc', $_POST['urldesc'] );
	}
}

That is obviously the most basic of ways to do it, but it works for what we want to do.

3. Adding The Metabox to your Custom Post Type

In order to make this all work, we of course need to add the functions to WordPress so it knows to do something with it. The hooks are required otherwise your metabox won't show or save when you submit it.

To add the metabox, we create a function which uses the add_meta_box() function, and pass it the information necessary for our metabox. You can read more about add_meta_box() here.

// Add action hooks. Without these we are lost
add_action( 'admin_init', 'add_custom_metabox' );
add_action( 'save_post', 'save_custom_url' );

/**
 * Add meta box
 */
function add_custom_metabox() {
	add_meta_box( 'custom-metabox', __( 'URL &amp; Description' ), 'url_custom_metabox', 'post', 'normal', 'high' );
}

This is adding our metabox function with the callback 'url_custom_metabox'. You can change the post type this will be added to by changing 'post' to whatever your post type you want to use it for.

4. Getting and Returning the Saved Data For Each Post

Finally, we need to have a way of displaying the information entered into the metabox fields on the frontend of the site, so we can make use of it right!

To do that, I like to just create a function that gets the post meta for me, and return the variables for each field I want as an array using get_post_meta() like this.

/**
 * Get and return the values for the URL and description
 */
function get_url_desc_box() {
	global $post;
	$urllink = get_post_meta( $post->ID, 'urllink', true );
	$urldesc = get_post_meta( $post->ID, 'urldesc', true );

	return array( $urllink, $urldesc );
}

The way you would use this in your theme is within whatever page template file, you create a variable and set it to this function. Then echo out the variable key you want to use. For example:

// get the array of data
$urlbox = get_url_desc_box();

echo $urlbox[0]; // echo out the url of a post
echo $urlbox[1]; // echo out the url description of a post

The $urlbox[0] will display the URL which can be used in the href of an anchor tag.

Here's The Entire Custom Metabox Code

You can either paste this into your functions.php file, or create a separate file within your theme directory, and use get_template_part( 'FILENAME' ); to include it in your functions file.

<?php

// Hook into WordPress
add_action( 'admin_init', 'add_custom_metabox' );
add_action( 'save_post', 'save_custom_url' );

/**
 * Add meta box
 */
function add_custom_metabox() {
	add_meta_box( 'custom-metabox', __( 'URL &amp; Description' ), 'url_custom_metabox', 'product', 'side', 'high' );
}

/**
 * Display the metabox
 */
function url_custom_metabox() {
	global $post;
	$urllink = get_post_meta( $post->ID, 'urllink', true );
	$urldesc = get_post_meta( $post->ID, 'urldesc', true );
	
	if ( !preg_match( "/http(s?):\/\//", $urllink )) {
		$errors = 'Url not valid';
		$urllink = 'http://';
	} 
	
	// output invlid url message and add the http:// to the input field
	if( $errors ) { echo $errors; } ?>
	
	<p><label for="siteurl">Url:<br />
		<input id="siteurl" size="37" name="siteurl" value="<?php if( $urllink ) { echo $urllink; } ?>" /></label></p>
	<p><label for="urldesc">Description:<br />
		<textarea id="urldesc" name="urldesc" cols="45" rows="4"><?php if( $urldesc ) { echo $urldesc; } ?></textarea></label></p>
<?php
}

/**
 * Process the custom metabox fields
 */
function save_custom_url( $post_id ) {
	global $post;	
	
	if( $_POST ) {
		update_post_meta( $post->ID, 'urllink', $_POST['siteurl'] );
		update_post_meta( $post->ID, 'urldesc', $_POST['urldesc'] );
	}
}

/**
 * Get and return the values for the URL and description
 */
function get_url_desc_box() {
	global $post;
	$urllink = get_post_meta( $post->ID, 'urllink', true );
	$urldesc = get_post_meta( $post->ID, 'urldesc', true );

	return array( $urllink, $urldesc );
}
?>

I've been making some pretty crazy metabox lately, and with WordPress 3.0, I think we're going to see a lot more need for people to be able to create them. My metaboxes are becoming more and more complex and customizable each time I make one. It's really cool, and worth taking the time to learn.

Hope this has helped you learn somethings about doing this. Let me know if you have any questions in the comments.

Shortlink:

Get automatic updates! Subscribe to Our RSS Feed or Get Email Updates sent straight to your inbox!

About the Author

Jared is from Boston working as a web and graphic designer. Also owns the design blog Tweeaks.com, and has designed many other websites powered by Wordpress including the New2WP theme.

Level: Noob

User Comments

( ADD YOURS )

  1. Is it possible to add custom metabox with image upload option? Can you able to create a tutorial for that. It would be awesome


  2. I actually did create a script that you can add/remove custom metaboxes that are upload fields for images, with form fields for each upload input field for the meta info of the images, and upon uploading or adding new ones, they are added to the post your currently editing as attachments, so they are associated to that post specifically. and they could/would be then used in the template file by checking for and calling the method which gets the images. It would resize the images automatically to the sizes that WP has set, just like the media gallery thickbox image uploader does, only with less gay thickbox slowness, that thing i hate so damn much. I had it at one time working to upload the images using ajax, so the upon selecting an image, it would upload and display the image you selected next to the input field right then immediately. already uploaded and attached to the post.

    its the slickness really, and i did begin writing the post, but then, of course, the whole project became just that, a project. it's was quite an effort i put in to get it to the point i did, trying to do it numerous times, and failing numerous times. I finally got it to work somewhat how i wanted it to and was so happy, but ran into so many issues with getting it ALL completely working the way i wanted it to, i never really completed it.

    The most recently and most stable working version of the code is on my github account. Fork it if you want, and use it, love it. whatever
    https://github.com/jaredwilli/attachments-metabox


  3. This is actually what I am looking for!!!Thank you for posting this…

Trackbacks


  1. Avatar

    Your Name
    May 23