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
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

Flowing topics will be discussed under this tutorial

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

How to create meta box

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

We need the callback function book_bookdetail_metabox_callback to generate the meta box

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

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.

Leave a Reply

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