How to Add Custom Meta Boxes in WordPress Posts

Do you want to create custom meta boxes for your WordPress posts, pages, and other post types? When a user edits a post, the edit screen is composed of several default boxes: Editor, Publish, Categories, Tags, etc. These boxes are meta boxes.

Most of the time, meta boxes in WordPress are created to increase better user experience by adding fields to your posts and page and even other post types. These fields are hidden from the user and you can decide how to display them to who.

Creating meta boxes in WordPress is simple. Plugins can add custom meta boxes to an edit screen of any post type. In this article, we are going to add our own meta boxes to WordPress posts and pages with our own fields.

What is a Custom Meta Box in WordPress?

Meta boxes are fields (Meta Data) in the post create or edit page on the admin side to add some features to increase theme functionality and user experience.

In WordPress users can create posts and pages, easily. Every post consists of its content and metadata. Metadata is information related to that content like date and time, author name, title, and more. In WordPress pages are stored in the post table, in fact, the page is kind of the post.

But this post creation sometimes doesn’t have enough features to display the content better. To add awesome features, we use meta boxes. You can also add your own metadata by using custom meta boxes fields.

How to add Custom Meta Boxes?

WordPress allows developers to add their own custom meta boxes on the post edit page on the admin side. That’s how most popular plugins add different options on your post edit screens.

For example, the SEO title and meta description box inside the “All in One SEO” plugin is a custom meta box. Now lets to create.

Creating Custom Meta Boxes in WordPress by plugin

You need to install the “Advanced Custom Fields” plugin at first. With this plugin, you can create custom fields with custom use.

After activation of the plugin, you will have a menu named “Custom Fields” in your dashboard menu.

With this plugin, you can create your own custom fields and use them anywhere you want.

Creating Custom Meta Boxes in WordPress programmatically

The content of the meta boxes is usually HTML form elements where the user enters data.

To create meta boxes open the “functions.php” file of your theme and add the code.

function hs_register_meta_boxes()
{
    add_meta_box('hs_post_options', __('Honar Systems Options', 'text-domain'), 'hs_options_callback', 'post');
    add_meta_box('hs_post_options', __('Honar Systems Options', 'text-domain'), 'hs_options_callback', 'page');
}
add_action('add_meta_boxes', 'hs_register_meta_boxes');

function hs_options_callback($post)
{
?>
    <h3><?php esc_html_e('Name', 'text-domain'); ?></h3>
    <input type="text" name="hs_name" id="hs_name" value="<?php echo esc_attr(get_post_meta(get_the_ID(), 'hs_name', true)); ?>" />

    <?php if ($post->post_type == 'post') : ?>
        <h3><?php esc_html_e('Last Name', 'text-domain'); ?></h3>
        <input type="text" name="hs_last_name" id="hs_last_name" value="<?php echo esc_attr(get_post_meta(get_the_ID(), 'hs_last_name', true)); ?>" />
    <?php endif; ?>
<?php
}

To create custom meta boxes we used add_meta_box() and plugged its execution into the add_meta_boxes action hook.

In this example, we created 2 meta boxes in WordPress that in posts, name and last name, and in pages only the name will be displayed.

How to Add Custom Meta Boxes in WordPress - Honar Systems

If you are going to display fields in custom post type, you can use the below code.

<?php if ($post->post_type == 'custom-post-type') : ?>
    <h3><?php esc_html_e('Last Name', 'text-domain'); ?></h3>
    <input type="text" name="hs_last_name" id="hs_last_name" value="<?php echo esc_attr(get_post_meta(get_the_ID(), 'hs_last_name', true)); ?>" />
<?php endif; ?>

Note: there is no submit button in meta boxes. All the post data including meta box values are transferred via POST method when the user clicks on the Publish or Update button.

Getting field value

These fields’ values are stored in postmeta the table in the database. To retrieve them, we will use get_post_meta() WordPress function.

As you see we used the function in the below code.

echo esc_attr(get_post_meta(get_the_ID(), 'hs_last_name', true));

the get_post_meta() takes 3 arguments. The first one is post ID, the second is the field ID and the last one is whether to return a single value. If there is no value for a field with “hs_last_name” ID, the function will return empty text.

Saving Values

When you enter or choose the value of the meta boxes, they are not saved until you click on Publish or Update button. When a post type is saved or updated, several actions fire, any of which might be appropriate to hook into in order to save the entered values. but we have to tell the WordPress we created custom meta boxes with their own IDs.

function hs_save_meta_options($post_id)
{
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if ($parent_id = wp_is_post_revision($post_id)) {
        $post_id = $parent_id;
    }
    $fields = [
        'hs_name',
        'hs_last_name',
    ];
    foreach ($fields as $field) {
        if (array_key_exists($field, $_POST)) {
            update_post_meta($post_id, $field, sanitize_text_field(wp_unslash($_POST[$field])));
        }
    }
}
add_action('save_post', 'hs_save_meta_options');

We can store the fields data anywhere we want, even another table in the database or even outside of our website. But in this example, we are dealing with post data then we stored them in the WordPress database with the post ID.

Note: Do not forget to sanitize data in saving them.

Removing Meta Boxes

Removing the existing meta box can be done by remove_meta_box() function.

Shopping Cart