PressTigers

How To Create Custom Post Meta Boxes In WordPress

A post meta box is a draggable box shown on the post editing screen. Its purpose is to allow the user to select or enter information in addition to the main post content. This information should be related to the post. Generally, two types of data is entered into meta boxes:

  • Metadata (i.e. custom fields)
  • Taxonomy terms.

Post Metadata:

Post Metadata is the data that is saved in wp_postmeta table in the database. Each entry is saved as the following four fields in this table:

  1. meta_id: A unique ID for a specific metadata
  2. post_id: The post ID to which this metadata is attached
  3. meta_key: A key which is used to identify Data (you’ll work with this often)
  4. meta_value: The value of metadata.

Building A Custom Post Meta Box:

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:

In the above code snippet, you added add_custom_meta_boxes() function to the add_meta_boxes hook. This function’s purpose is to add post meta boxes. Before proceeding further, add_meta_box() function includes the following parameters:

  • $id: This is a unique ID assigned to your meta box. It should have a unique prefix and be valid with HTML
  • $title: This is a title of the meta box. You have to internationalize this for translators
  • $callback: The callback function displays the output of your meta box
  • $page: The admin page to display the meta box. In our case, this would be the name of the post type (post, page, or a custom post type)
  • $context: A place on web page where meta box should be shown. The available options are normal, advanced, and side
  • $priority: How high/low of the meta box should be prioritized. The available options are default, core, high, and low
  • $callback_args: An array of custom arguments you can pass to your $callback function as the second parameter

The following code will then add the post meta box to the post editor screen:

We still need to display the meta box’s HTML though which is custom_post_meta_boxes function here:

At this point, you should have a nice-looking meta box on your post editing screen.

Save Meta Box Data:

We have created a meta box and it’s time now to save post metadata as follows:

That function will actually look like this:

Now the meta value is saved. You can get the post meta value where you need by:

User Comments

Leave a Reply

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

Get in Touch