Create a custom meta box in WordPress - WPTRINITY

Create a custom meta box in WordPress

What Is Post Metadata?

Post metadata is the extra information of post which we are attached or add with post and this postmeta data that’s saved in wp_postmeta table in the database. Each entry is saved as four fields in this table:

1 meta_id: A unique ID for this specific metadata.

2 post_id: The post ID this metadata is attached to.

3 meta_key: A key used to identify the data (you’ll work with this often).

4 meta_value: The value of the metadata.

In the following screenshot, you can see how this looks in the database.

When you get right down to it, metadata is just key/value pairs saved for a specific post. This allows you to add all sorts of custom data to your posts. It is especially useful when you’re developing custom post types.

The only limit is your imagination.

Note: One thing to keep in mind is that a single meta key can have multiple meta values. This isn’t a common use, but it can be extremely powerful.

Use Post Metadata

To understand how custom meta boxes are useful, you must understand how to add, update, delete, and get post metadata.

add_post_meta()”): Adds post metadata.

update_post_meta()”): Updates post metadata.

delete_post_meta()”): Deletes post metadata.

get_post_meta()”): Retrieves post metadata.

The Setup Postmeta box

Before building post meta boxes, you need have some ideas about what type of metadata you want to use. This example will focus on create a meta box that saves a custom post CSS class, which can be used to style posts.

I’ll start you off by teaching you to develop custom code that does a few extremely simple things:

  • Adds an input box for you to add a custom post class (the meta box).
  • Saves the post class for the wp_post_class meta key.
  • Filters the post_class hook to add your custom post-class.

You can do much more complex things with meta boxes, but you need to learn the basics first.

All of the PHP code in the following sections goes into your theme’s functions.php file.

Create A Custom Post Meta Box

Now you only want your post meta box to appear on the post editor screen in the admin, you’ll use the load-post.php and load-post-new.php hooks to initialize your meta box code.

/* Fire our meta box setup function on the post editor screen. */
add_action( 'load-post.php', 'wp_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'wp_post_meta_boxes_setup' );


Most WordPress developers should be familiar with how hooks work, so this should not be anything new to you. The above code tells WordPress that you want to fire the wp_post_meta_boxes_setup function on the post editor screen. The next step is to create this function.

The following code snippet will add your meta box creation function to the add_meta_boxes hook. WordPress provides this hook to add meta boxes.

/* Meta box setup function. */
function wp_post_meta_boxes_setup() {

/* Add meta boxes on the ‘add_meta_boxes’ hook. */
add_action( ‘add_meta_boxes’, ‘wp_add_post_meta_boxes’ );

In the above code snippet, you added the wp_add_post_meta_boxes() function to the add_meta_boxes hook. This function’s purpose should be to add post meta boxes.

In the next example, you’ll create a single meta box using the add_meta_box() WordPress function. However, you can add as many meta boxes as you like at this point when developing your own projects.

Before proceeding, let’s look at the add_meta_box() function:

add_meta_box( $id, $title, $callback, $page, $context = 'advanced', $priority = 'default', $callback_args = null );


  • $id: This is a unique ID assigned to your meta box. It should have a unique prefix and be valid HTML.
  • $title: The title of the meta box. Remember to internationalize this for translators.
  • $callback: The callback function that displays the output of your meta box.
  • $screen: The screen or screens on which to show the box (such as a post type, link, or comment). Accepts a single screen ID, WP_Screen object, or array of screen IDs. Default is the current screen.
  • $context: Where on the page the meta box should be shown. The available options are normaladvanced, and side.
  • $priority: How high/low the meta box should be prioritized. The available options are defaultcorehigh, and low.
  • $callback_args: An array of custom arguments you can pass to your $callback function as the second parameter.

The following code will add the post class meta box to the post editor screen.

/* Create one or more meta boxes to be displayed on the post editor screen. */
function wp_add_post_meta_boxes() {

    'wp-post-class',      // Unique ID
    esc_html__( 'Post Class', 'example' ),    // Title
    'wp_post_class_meta_box',   // Callback function
    'post',         // Admin page (or post type)
    'side',         // Context
    'default'         // Priority

You still need to display the meta box’s HTML though. That’s where the wp_post_class_meta_box() function comes in ($callback parameter from above).

/* Display the post meta box. */
function wp_post_class_meta_box( $post ) { ?>

  <?php wp_nonce_field( basename( __FILE__ ), 'wp_post_class_nonce' ); ?>

    <label for="wp-post-class"><?php _e( "Add a custom CSS class, which will be applied to WordPress' post class.", 'example' ); ?></label>
    <br />
    <input class="widefat" type="text" name="wp-post-class" id="wp-post-class" value="<?php echo esc_attr( get_post_meta( $post->ID, 'wp_post_class', true ) ); ?>" size="30" />
<?php }


What the above function does is display the HTML output for your meta box. It displays a hidden nonce input (you can read more about nonces on the WordPress Codex). It then displays an input element for adding a custom post class as well as output the custom class if one has been input.

At this point, you should have a nice-looking meta box on your post editing screen. It should look like the following screenshot.

The meta box doesn’t actually do anything yet though. For example, it won’t save your custom post class. That’s what the next section of this tutorial is about.

Saving The Meta Box Data

Now after that it’s time to learn how to save post metadata.

Remember that wp_post_meta_boxes_setup() the function you created earlier? You need to modify that a bit. You’ll want to add the following code to it.

/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'wp_save_post_class_meta', 10, 2 );


So, that function will actually look like this:

/* Meta box setup function. */
function wp_post_meta_boxes_setup() {

  /* Add meta boxes on the 'add_meta_boxes' hook. */
  add_action( 'add_meta_boxes', 'wp_add_post_meta_boxes' );

  /* Save post meta on the 'save_post' hook. */
  add_action( 'save_post', 'wp_save_post_class_meta', 10, 2 );


The new code you’re adding tells WordPress that you want to run a custom function on the save_post hook. This function will save, update, or delete your custom post meta.

When saving post meta, your function needs to run through a number of processes:

  • Verify the nonce set in the meta box function.
  • Check that the current user has permission to edit the post.
  • Grab the posted input value from $_POST.
  • Decide whether the meta should be added, updated, or deleted based on the posted value and the old value.

I’ve left the following function somewhat generic so that you’ll have a little flexibility when developing your own meta boxes. It is the final snippet of code that you’ll need to save the metadata for your custom post class meta box.

/* Save the meta box’s post metadata. */
function wp_save_post_class_meta( $post_id, $post ) {

  /* Verify the nonce before proceeding. */
  if ( !isset( $_POST['wp_post_class_nonce'] ) || !wp_verify_nonce( $_POST['wp_post_class_nonce'], basename( __FILE__ ) ) )
    return $post_id;

  /* Get the post type object. */
  $post_type = get_post_type_object( $post->post_type );

  /* Check if the current user has permission to edit the post. */
  if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
    return $post_id;

  /* Get the posted data and sanitize it for use as an HTML class. */
  $new_meta_value = ( isset( $_POST['wp-post-class'] ) ? sanitize_html_class( $_POST['wp-post-class'] ) : ’ );

  /* Get the meta key. */
  $meta_key = 'wp_post_class';

  /* Get the meta value of the custom field key. */
  $meta_value = get_post_meta( $post_id, $meta_key, true );

  /* If a new meta value was added and there was no previous value, add it. */
  if ( $new_meta_value && ’ == $meta_value )
    add_post_meta( $post_id, $meta_key, $new_meta_value, true );

  /* If the new meta value does not match the old value, update it. */
  elseif ( $new_meta_value && $new_meta_value != $meta_value )
    update_post_meta( $post_id, $meta_key, $new_meta_value );

  /* If there is no new meta value but an old value exists, delete it. */
  elseif ( ’ == $new_meta_value && $meta_value )
    delete_post_meta( $post_id, $meta_key, $meta_value );


At this point, you can save, update, or delete the data in the “Post Class” meta box you created from the post editor screen

Using The Metadata From Meta Boxes

So you have a custom post meta box that works, but you still need to do something with the metadata that it saves. That’s the point of creating meta boxes. What to do with your metadata will change from project to project, so this is not something I can answer for you. However, you will learn how to use the metadata from the meta box you’ve created.

Since you’ve been building a meta box that allows a user to input a custom post class, you’ll need to filter WordPress’ post_class hook so that the custom class appears alongside the other post classes.

Remember that get_post_meta() function from much earlier in the tutorial? You’ll need that too.

Leave a Comment

Your email address will not be published. Required fields are marked *