Shelley Bassett



How To Use Custom Metadata

July 16, 2018

If your posts have custom fields, you might be wondering how to use custom metadata. This tutorial walks through calling and displaying custom fields in the WordPress loop.

Many plugins offer custom fields for posts. We’ve even spoken about how to add this metadata via a plugin or theme. But how do you use custom metadata? It’s pretty simple, and involves calling the field from the database, then displaying it on a page in the theme.Custom metadata lets you store almost anything as a part of the post. It’s a powerful way to add elements that will be common to an entire post type, and it’s easily added to both the standard WordPress posts as well as custom post types. But once this data is saved, it has to be specifically called to display on a page.

Use Custom Metadata on a Theme Page

Custom metadata can be called on any page in a theme. This is due to it being saved as part of a post. Provided you are looping through posts, you can access and use custom metadata. The following example uses the standard WordPress loop to display the post title and a custom meta field. It’s calling the  '_app_data'  meta from the previous example. This is a good test to check that the loop is calling the correct metadata for the post.

Make sure the metadata name you call in the function (here '_app_data' ) is the same name that it was saved under. And easy way to check is to review your custom metadata save script. Each piece of metadata will have it’s own unique identifying name, allowing you to call anything multiple times.

Displaying the Metadata

I’ve used the wpautop()  function to display the metadata, although that’s not necessary. You might just want to echo the string, or some HTML tags to surround it. But for this application I chose use  wpautop()  because that will wrap each line in <p></p>  tags, creating the body of a blog post.

It’s up to you to decide how to display your custom metadata. You can use custom metadata for so many things that you might want to echo the string as an alt tag for an image. Or as a hyperlink to a video. The example we’ve worked though added an application guide to a product page, which is why I chose to use  wp_editor()  and wpautop()  to create and display my text. It preserves the formatting both during saving and displaying, a handy hint to know when working on large or complex posts.