How to create Meta Box in WordPress

In this tutorial we will see how to add meta box to post editing screen in admin section of the WordPress

What is Metabox in WordPress?

In WP admin section, you can see the draggable boxes inside the post editing screen and these boxed are called Meta Boxes. You can store attributes for the post using this Meta box

WP Custom Field is popular Metabox you will find your post editing screen


Meta box can be used to enter additional data related to the post. This meta box is draggable box you can use inside post editing screen. You can enter two types of data inside the meta box

  1. Meta Data (Custom Fields)
  2. Taxonomy terms

Now I am going to explain following topics in this tutorials.

  • How to create meta box in WP
  • How to save custom meta data to post in WP
  • How to retrieve custom meta data from post in WP
  • How to retrieve custom meta data to display in front end in WP

How to create meta box

You can use the following code to create the Meta Box for the custom post type book.

 The add_meta_box() is used to add meta box to any post type when editing and subsequently you can use h add_meta_boxes action to hook the function  eventcal_eventdetail_meta_box() 

We need the callback function book_bookdetail_metabox_callback to generate the meta box

Author Name

Once you create the callback function you have to call the action hook add_meta_boxes with the callback function

You can see the following screen in your WordPress admin for the above code snippet

How to save custom meta data

Now we will see how you can save the custom meta data to the database. To save custom meta data, you can use the save_post action which will be triggered whenever post is created or updated. So you can use the following code

Here save_book_meta is a function where we write the code to save meta data to the database.
Following code shows how you can save meta data to the database

How to retrieve custom meta data

To retrieve the data from the database you can use the get_post_meta() function. I have changed the book_bookdetail_metabox_callback function as shown in the below code. You can see value attribute of the input html tag

Author Name
1
2
<!--?php }
</pre-->

How to retrieve custom meta data to display in front end

You can use the get_post_meta() function show the meta data in the WordPress front end.