Custom Meta Box in WordPress Post Pages and Custom Post Type

WordPress custom meta boxes are those that hold additional meta information for a post, page or custom post types. The custom meta boxes are generally seen below the post editor, but depending on the setting, it may also appear before the editor or in the sidebar. The meta boxes are also features drag and drop, that means, you can reposition the boxes as per your need. If you want to display additional information along with a normal WordPress post, custom meta boxes are the only way to go.

You may find tons of tutorials on how to add WordPress custom meta box with thousands of lines on code making it look like pretty complicated to add WordPress custom meta boxes, but it is actually very simple if you break the whole code part by part. All you need to understand what the basics are and how WordPress custom meta boxes operate. The WordPress codex to add demonstrate a simple way to add custom meta box in WordPress, and let me help you understand it better.

wordpress custom meta box

WordPress Custom Meta Box Basics

Three simple steps is all it requires to add your first WordPress custom meta box. Here is the breakdown of the steps:

  1. Add The Custom Meta Box
  2. Create The Custom Meta Box Fields
  3. Save The Custom Meta Box Field Values

Add Custom Meta Box

The function that adds the custom meta box is add_meta_box which should be wrapped in callback and hooked to add_meta_boxes action. Here is the code:

function add_custom_meta_box() {
	add_meta_box( $id, $title, $callback, $post_type, $context, $priority, $callback_args );
}
add_action( 'add_meta_boxes', 'add_custom_meta_box' );

Here is what each parameter does. For more information see the Codex Page:

  • $id: The ID of the meta box. Should be unique for each meta box.
  • $title: The title of the Meta box.
  • $callback: The function that generates the HTML (input fields, descriptions etc.) within the meta box.
  • $post_type: An array of the post types where you want the meta box to appear.
  • $context: Where in the edit screen the meta box should appear.
  • $priority: The priority of the metabox.
  • $callback_args: The arguments to pass to the callback function that generates the HTML of the meta box.

Create The Custom Meta Box Fields

Now that you added the custom meta box, you need to add the fields to input data in the meta fields. This is done using the callback function we used as the $callback parameter in add_meta_box function. You can add as many input fields of any input type as you want. Here is the sample code that adds a text field, checkbox and radio buttons.

function add_meta_box_fields( $post ) {
// Add nonce to check for legal requests
 wp_nonce_field( 'add_meta_box_fields', 'my_metabox_nonce' );
$textfield = get_post_meta( $post->ID, '_my_meta_text_field', true );
$selectfield = get_post_meta( $post->ID, '_my_meta_select_field', true );
$checkfield = get_post_meta( $post->ID, '_my_meta_check_field', true ); ?>

	<p>
		<label for="text_field">Text Field Label</label>  
		<input type="text" name="text_field" id="text_field" value="<?php echo $textfield; ?>" />
	</p>

	<p>
		<label for="select_field">Select Field Label</label>  
        <select name="select_field" id="select_field">  
            <option value="red" <?php selected( $selectfield, 'red' ); ?>>Red</option>
            <option value="blue" <?php selected( $selectfield, 'blue' ); ?>>Blue</option>
			<option value="yellow" <?php selected( $selectfield, 'yellow' ); ?>>yellow</option>
			<option value="green" <?php selected( $selectfield, 'green' ); ?>>Green</option>
        </select> 
	</p>

	<p>
		<label for="">Multicheck Field Label</label>
		<input type="checkbox" name="check_field" value="value1" <?php checked( $checkfield, 'value1' ); ?>>Checkbox 1<br>
		<input type="checkbox" name="check_field" value="value2" <?php checked( $checkfield, 'value2' ); ?>>Checkbox 2<br>
		<input type="checkbox" name="check_field" value="value3" <?php checked( $checkfield, 'value3' ); ?>>Checkbox 3
	</p>
<?php  
}

Save The Custom Meta Box Fields

When someone enters a value in the fields or edits the value, we need to save it with the post. Note that the meta data doesn’t get saved with the wp_posts table in database, rather it goes into the wp_postmeta table. So, when you try to change the value manually from database, don’t bother to look into the wp_posts table.

The function that saves to values to database is update_post_meta, wrapped in a callback and hooked into the save_post action. Here is the code that saves our fields.

function save_meta_values( $post_id ) {
//Get the nonce first
$nonce = $_POST['ia_deals_meta_box_nonce'];
  // If nonce isn't set
  if ( ! isset( $nonce ) ) return $post_id;

  // If nonce is set verify that the nonce is valid.
  if ( ! wp_verify_nonce( $nonce, 'ia_deals_meta_box' ) )
      return $post_id;

  // If this is an autosave, our form has not been submitted, so we don't want to do anything.
  if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) 
      return $post_id;

  // Check the user's permissions.
  if ( 'page' == $_POST['post_type'] ) {

    if ( ! current_user_can( 'edit_page', $post_id ) )
        return $post_id;

  } else {

    if ( ! current_user_can( 'edit_post', $post_id ) )
        return $post_id;
  }

  // Sanitize user input.
  $textdata = sanitize_text_field( $_POST['text_field'] );
  $selectdata = sanitize_text_field( $_POST['select_field'] );
  $checkdata = sanitize_text_field( $_POST['check_field'] );

  // Update the meta field in the database.
  update_post_meta( $post_id, '_my_meta_text_field', $textdata );
  update_post_meta( $post_id, '_my_meta_select_field', $selectdata );
  update_post_meta( $post_id, '_my_meta_check_field', $checkdata );
}
add_action( 'save_post', 'save_meta_values' );

That’s all. Our meta data now gets saved or updated along with the post. Now it’s time to retrieve the value and display at front end.

Retrieving The Meta Value

The function that retrieves the value of the custom meta field is get_post_meta.

get_post_meta( $post_id, $key, $single );

Here is what each parameter does. For more information see the Codex Page:

  • $post_id: The ID of the current post. If in a loop, use get_the_ID().
  • $key: The key to the meta value you want to retrieve.
  • $single: Whether to return the first value in case of multiple values stored against a single key.

We stored single values for the first two fields, i.e text and select in our example code, but in case of the checkboxes, if the user checks all three, three different values will be stored against the single key. Lets see how to grab them properly.

For text field:

get_post_meta( get_the_ID(), '_my_meta_text_field', true );

For select field:

get_post_meta( get_the_ID(), '_my_meta_select_field', true );

For Checkbox Field:

$checkboxmetas = get_post_meta( get_the_ID(), '_my_meta_check_field' );
	foreach ($checkboxmetas as $checkboxmeta) {
		echo 'Checkbox Field Value: ' . $checkboxmeta . '<br>';
	}

Hope that helps you to understand and implement the custom meta box in WordPress. If you like it, or need help, feel free to post your message in the comments.

Get Updates In Your Inbox

Get the WordPress Tips and latst Internet Marketing ideas delivered directly to your email inbox, plus access to our FREE Pro Blogging Model blogging guide.

You need to confirm your email once. Don't worry, we hate SPAMs as much as you do

Speak Your Mind

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

You may use these HTML Tags and Attributes

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>