How to Add Metabox | Save & Get Meta box Value in WordPress

Meta boxes in WordPress are the draggable boxes that exist in WordPress admin. It contains form fields to set information about the post, page, custom post type, terms, users, comments etc.

Meta box can also be used to display information like in the WordPress dashboard. By default, WordPress comes with some metaboxes that exist in the edit screen of a post or page as shown in the below image. Eg: editor, featured image, post format, category, template etc.

default wordpress metaboxes examples

WordPress Custom Meta Box

Apart from the default WordPress meta boxes, you can also create your own metabox or custom metabox.

Custom Metabox allows users to add some additional or extra piece of information about its associated information. That means, metabox provides a way to extra information for the post, page, custom post types, users, comments, terms etc.

You can create custom meta boxes for your theme or plugin as well to provide the option to set extra data along with its associated data.

How To Add WordPress Custom Metabox to Post, Page & Custom Post Type

To create or add a custom metabox, WordPress provides a function that accepts some parameters and based upon the value of these parameters, it adds a metabox.

add_meta_box( $id, $title, $callback_function, $screen, $context, $priority, $callback_args );

The above function will help you to add a custom WordPress metabox. The parameters are:

  • $id – It’s a required parameter and it should be string. This refers to the meta box ID that will be used in the id=”” attribute of the metabox.
  • $title – It’s required and refers to the meta box title.
  • $callback_function – It’s required and refers to the callback function name that will fill this metabox with desired content. Note: your callback function should echo its output.
  • $screen – It can be string or an array of screens. This parameter tells where the metabox should display.
    1. screen means the edit or add new page of posts, pages, or any custom post types.
    2. If you want to add metabox for the post type then you can set $screen = ‘post’
    3. If you want to add metabox for the pages then you can set $screen = ‘page’
    4. If you want to add metabox for the custom post type then you can set $screen = ‘your_custom_post_type_name’
    5. If you want to add metabox in multiple screen then you can pass the screens in an array like array(‘post’, ‘page’, ‘custom_post_type’)
    6. If you have created a new screen by using add_menu_page() or add_submenu_page() then you can use the menu slug for the screen.
  • $context –  Where the metabox should display in that particular screen. It accepts values like: ‘normal’, ‘advanced’, & ‘side’. Default value is ‘advanced’
  • $priority – the priority indicates, whether the metabox should display above or below of any other metabox. Accepted Value: default | high | low 
  • $callback_args – an array of the data that should be set as the property of the metabox. This should be passed as a second parameter in your callback function. The default value is null.

WordPress Metabox Hook

To execute meta boxes, you have to use add_meta_boxes metabox hook with WordPress.

add_action( 'add_meta_boxes', 'your_metabox_functiona_name' ); 

The below code snippet will add a custom metabox in the post screen. That will simply display a welcome message. To see this in action, add this code in your theme’s functions.php file or in your plugin specific file.

//Add Custom Metabox
function diwp_custom_metabox(){

	add_meta_box( 
			'diwp-metabox',
			'My Custom Metabox',
			'diwp_custom_metabox_callback',
			'post'
		  );
}

add_action('add_meta_boxes', 'diwp_custom_metabox');


function diwp_custom_metabox_callback(){
	echo "Hello Everyone!. This is my first custom metabox";
}

This code above will add the metabox in the post screen as shown in the image below.

custom metabox with welcome message

How to add form (input) fields in custom metabox

Now in the next step, I will add the form fields or input fields in the above metabox.

When we add form fields or input fields in metabox, then there is no need to add form tag and submit button because the metabox’s fields get submitted along with the associated post or page or on whatever screen it is.

I am just extending the above code, so just remove everything inside the function diwp_custom_metabox_callback from the above code.

function diwp_custom_metabox_callback(){
 
// Remove everything

}

And copy the below code and add it inside the function diwp_custom_metabox_callback.

	?>
	<div class="row">
    	<div class="label">Post Reading Time</div>
    	<div class="fields">
    		<input type="text" name="_diwp_reading_time" value=""/>
    	</div>
	</div>
	<?php

This will add a text field in the metabox as showing in the image below. In the next step, I will save the value of this metabox field.

custom metabox with input field

Save Meta Box Value in WordPress

To save metabox’s input fields value, WordPress provides a hook that is called ‘save_post‘. So this hook should be executed when we save our metabox’s fields value.

add_action( ' save_post ', ' function_name_that_hold_the_code_to_update_fields ' );

Now to update or save meta box field in the database, WordPress has a function called

 update_post_meta($post_id, $meta_key, $meta_value, $prev_value); 

This function updates the value of the meta key and if there is no meta key exists then it creates the meta key.

  1. $post_id – It’s required and refers to the Post ID.
  2. $meta_key – It’s required and refers to the name of your metadata key, that will hold the value of the metabox field in the database.
  3. $meta_value – It’s required, value of metadata.
  4. $prev_value – It’s optional, it refers to the previous value to check before updating.

So back to our code, to save the value of my custom metabox’s field, I will use the update_post_meta function along with save_post hook.

Copy the code below and add this into your theme’s functions.php file.


function diwp_save_custom_metabox(){

	global $post;

	if(isset($_POST["_diwp_reading_time"])):
		
		update_post_meta($post->ID, 'post_reading_time', $_POST["_diwp_reading_time"]);
	
	endif;
}

add_action('save_post', 'diwp_save_custom_metabox');

This code will save the metabox value in the database. In the next step, I will show you how to get metabox value.

Get Metabox Value In WordPress

To get the value of the metabox field, WordPress has a function called get_post_meta().

get_post_meta($post_ID, $meta_key, $single);
  1. $post_id– It’s required and refers to the post id.
  2. $meta_key – the name of the meta key to retrieve data.
  3. $single – It accepts true or false. If true then, it will retrieve the first or single value of the specified meta key.

So back to our code, I will use this function to get the value of my custom metabox fields.

echo get_post_meta( $post->ID,  'post_reading_time', true );

Add the above code wherever you want to display the value of the metabox field.

Display Updated Value in Metabox’s Field

Once you are done with updating metabox’s field in wordpress backend, it’s important to fill that field with updated value.

So to do that, all you need to do is first call a global variable for post to access the current post id and then use the get_post_meta() function inside the value attribute of the field.

  1. Call Global Variable: Inside the function diwp_custom_metabox_callback, define a global variable for post, as shown below
     
    
    function diwp_custom_metabox_callback(){
    global $post;
    
    // rest of the code goes here….
    
  2. Then add get_post_meta() function with the meta key in the value attribute of metabox’s field.
    	<input type="text" name="_diwp_reading_time" value="<?php echo get_post_meta($post->ID, 'post_reading_time', true)?>"/>
    

Complete Code To Add Custom WordPress Metabox, Save & Get Metabox Value in WordPress

Here is the full code snippet, you can directly copy this complete code and paste it into your theme’s functions.php file to add a custom metabox and save, get its value.

//Add Custom Metabox
function diwp_custom_metabox(){

	add_meta_box( 
					'diwp-metabox',
					'My Custom Metabox',
					'diwp_custom_metabox_callback',
					'post',
					'normal'
				);
}

add_action('add_meta_boxes', 'diwp_custom_metabox');


function diwp_custom_metabox_callback(){
	
	global $post;
	
	?>

	<div class="row">
    	<div class="label">Post Reading Time</div>
    	<div class="fields">
    		<input type="text" name="_diwp_reading_time" value="<?php echo get_post_meta($post->ID, 'post_reading_time', true)?>"/>
    	</div>
	</div>

	<?php

}

function diwp_save_custom_metabox(){

	global $post;

	if(isset($_POST["_diwp_reading_time"])):
		
		update_post_meta($post->ID, 'post_reading_time', $_POST["_diwp_reading_time"]);
	
	endif;
}

add_action('save_post', 'diwp_save_custom_metabox');

I hope this article helps you to understand how to add a custom metabox with WordPress and How to save and Get metabox value in WordPress.

Owner of diveinwp.com, solely responsible for creating helpful, informative content about WordPress, a fulltime WordPress developer with 8+ years of hands-on experience in WordPress design and development.

5 thoughts on “How to Add Metabox | Save & Get Meta box Value in WordPress”

  1. Hello Bhuvnesh Shrivastava, I am a junior WordPress developer. this article is very complete about metaboxes and easy to follow.
    Thank you so much more making it. It helped me a lot. Keep going good works man.

    1. Bhuvnesh Shrivastava

      Hi Ali,

      Thanks you so much, keep visiting Dive in WP for more upcoming WordPress stuff.

Comments are closed.