Tutorials 20 January 2021

WordPress Meta Boxes – A Quick Guide

Tassos Antoniou

8 min read
Image for WordPress Meta Boxes – A Quick Guide

WordPress Meta Boxes are draggable boxes that show in your editing screen and are used to handle additional data such as Taxonomy terms. In this article we’re going to take a look at WordPress meta boxes and see how we can our own custom ones, find out how to save the changes we make and how we can display their content on the front end of our website.

Let’s get started!

Custom Fields, Meta boxes and Metadata

There is a lot of confusion out there about the difference between these three terms. Let’s take a look at all three to get a better understanding of what they are and how they work.

Metadata

A post’s meta data is the extra information about a post that is stored in the database postmeta table.

Every key/value pair is considered a ‘post field’. There are no limits on how many meta entries this table can have.

Custom Fields

There are fields that are predefined by WordPress like the feature image which are technically custom fields. Others can be added by a plugin or custom code and defined by the admin user. You can find out more about custom fields by reading our article ‘Getting Started with WordPress Custom Fields‘.

Metaboxes

When you open a WordPress post to edit it you’ll see the page is broken up into different sections (many of which are located in the sidebar on the right hand side).

All of these sections are technically ‘meta boxes’. So, the main post editor, the containers for choosing categories, publishing the post, adding tags, adding a featured image are all meta boxes that contain HTML elements that interact with the post’s metadata. Depending on how the metadata is handled by the website, these boxes will appear in different locations on your screen.

By way of further example, let’s look at the Featured Image meta box. This is normally found in the right hand sidebar of a post’s admin screen. There, you can easily change the image. When you do this, you are actually updating the _thumbnail_id of that post’s metadata.

A custom field meta box, like the ‘source’ (that we added in our tutorial on Custom Fields) , can be usually found below the main post editor.

Creating a Meta Box for our Custom Post Type

Now we’ve got a clearer idea of what exactly meta boxes are, we can move on and build our own custom meta box for our website. This tutorial follows on from our tutorial on Custom Post Types… if you want to follow along step-by-step then you’ll need to check out that article and create a custom post type called ‘recipes’ and then setup couple of ‘recipes’ test posts with a featured image selected.

In this tutorial we are going to expand on our custom post type by adding in a new meta box that will be used to define whether the recipe is vegan or not by ticking a checkbox.

Step 1 – Register the Meta Box

To add a meta box in our custom post type we use the add_meta_box function provided by WordPress. Here is the structure of the function with the arguments that we will use:

add_meta_box( $id, $title, $callback, $screen, $context )

For the unique id we will use is_vegan and for the title of the meta box the string Is Vegan.

The callback function to show the box content will be display_vegan_meta_box. The $screen attribute refers to the admin screen in which the meta box will be displayed on. In our case, this is the recipe’s post edit area, so it will be the unique post type name which as mentioned before is recipes. The $context parameter varies according to the admin screen.

The Post edit screen contexts that we will use here includes normal, side, and advanced as the available context values. We will use the side value to display the meta box in the sidebar of the post edit page.

So, in summary, using the parameters defined above the code that we should add in our my-custom-post-type.php should look like this:

function my_metabox() {
    add_meta_box( 'is_vegan', 'Is Vegan', 'display_vegan_meta_box', 'recipes', 'side' );
}
add_action( 'admin_init', 'my_metabox' );

As you will see, we used the admin_init hook which is triggered before any other hook when a user accesses the admin area.

Now, if you visit the edit page of a recipe post you should see the box in the sidebar. Of course, the content is currently empty.

The next step is to fill the box with the desired content.

Step 2 – Display the Meta Box Basic Content

We’ll be keeping the content of this box simple. All we need is a description and a checkbox. As mentioned, the content is returned in the display_vegan_meta_box function.

Please proceed and add the piece of code below under the my_metabox function:

function display_vegan_meta_box( $recipe ) {
    ?>
    <span class="title">Vegan recipe?</span>
    <span class="content"><label for="vegan_checkbox">
        <input type="checkbox" name="vegan_checkbox" id="vegan_checkbox" value="yes" />
    </label></span> 
 
    <?php
}

What we did in this function is output an HTML checkbox which for now is unchecked. After we introduce the save function, we will return to this section of code to make some more changes so that when the post edit page loads, the checkbox will retrieve the saved checkbox state.

Step 3 – Save the Meta Box Value to the Database

To save the metabox’s input fields value, we use the save_post action hook that WordPress provides like this:

function update_vegan_box( $post_id ) {
    if( !current_user_can( 'edit_post' ) ) return;
    if ( 'recipes' == get_post_type() ) {
        if ( isset( $_POST['vegan_checkbox'] ) && $_POST['vegan_checkbox'] != '' ) {
            update_post_meta( $post_id, 'is_vegan', $_POST['vegan_checkbox'] );
        }else {
            update_post_meta( $post_id, 'is_vegan', "no" );
        }
    }
}
add_action( 'save_post', 'update_vegan_box' );

Inside the update_vegan_box function with the $post_id argument we included some conditions. We first want to check whether the user has permission to edit the post and also make sure that we are editing a recipes post type.

So, if the post belongs to the recipes type we examine the value of the checkbox. Remember that by default, when the checkbox is checked, the database value that is stored is ‘yes’ and if not then the value is NULL. We tweaked this a bit so the ‘no’ value is saved when we save the post with the vegan meta box unchecked.

Here we used the update_post_meta WordPress function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' )

In its arguments, we defined the post id, meta key, meta value. The function can accept one more argument though, the $prev_value
in-case we want to check the previous value before updating and only if it is equal, proceed and update.

Step 4 – Refine the Meta Box Content Code

Now let’s return to the previous function that outputs the meta box content and add some more lines of code that retrieve the related data from database.

function display_vegan_meta_box( $recipe ) {
	$is_value = esc_html( get_post_meta( $recipe->ID, 'is_vegan', true ) );
	$checked;
	if ( $is_value == "yes" ) { $checked = "checked"; } 
	else if ( $is_value == "no" ) { $checked = ""; } 
	else { $checked="";}
    ?>
    <span class="title">Vegan recipe?</span>
    <span class="content"><label for="vegan_checkbox">
        <input type="checkbox" name="vegan_checkbox" id="vegan_checkbox" value="yes" <?php echo $checked; ?> />
    </label></span> 
 
    <?php
}

So, first we retrieve the is_vegan meta value and then if appropriate, the checked value will be passed to the $checked variable and will be echoed in the HTML output.

And that’s it. We now have a working meta box that can be used to define whether the recipe in our custom post is vegan or not.

Conclusion

Meta boxes offer an increased level of control and flexibility in posts and can be leveraged in a variety of ways. What’s especially nice about them is that they are separated from the rest of the content of the post whilst at the same time residing on the same admin screen which makes managing them much easier than if they were located eslewhere in the WordPress Admin.

As with most WordPress coding, it can take a while to get familiar with using meta boxes. Hopefully the information above is enough to get you started. Happy coding!

Host your WordPress Website with Pressidium!

View our price plans

Host your website with Pressidium

60-DAY MONEY BACK GUARANTEE

SEE OUR PLANS

Do you like this article?

Subscribe to our blog and get awesome WordPress content straight to your inbox.

SUBSCRIBE

OUR READERS ALSO VIEWED:

Filter Content Using Tags in WordPress

Filter Content Using Tags in WordPress

Got a large website? Then you might be looking at ways of helping your users filter certain content. Tags might be the perfect solution.
Tassos Antoniou
Tassos Antoniou
9 min read
Using WebP Images in WordPress

Using WebP Images in WordPress

As you’re probably already aware, when it comes to websites, speed matters! One of the top things you can do to speed up your website is by reducing the page size. The smaller it is, the less data that has to be downloaded. The less data,…
Alexander Newnham
Alexander Newnham
8 min read
Adding Fields to WordPress Menu Items

Adding Custom Fields to WordPress Menu Items

Want to jazz up your WordPress menu with some custom fields? Find out how with this step-by-step tutorial.
Tassos Antoniou
Tassos Antoniou
7 min read
The Core Design Principles Behind the Pressidium Brand

The Core Design Principles Behind the Pressidium Brand

Brand guidelines can help shape a company. Take a look at our values, philosophy and (of course) how we design here at Pressidium!
Ioanna Aravani
Ioanna Aravani
6 min read
SUBSCRIBE