WordPress has the ability to allow the author to assign custom fields to posts. Custom fields are extra information known as meta data. Each meta data contains a key and a value. Where key is the name of the meta data and value is the information.You can use the same key name across multiple posts, while giving each post a different value. Think of it like authors to a blog. Let me expand on this. Let’s say a blog has multiple authors, the word author would be the key and the name of the author would be the value. But the custom fields allows you to create your own, which is fantastic!

Create the Custom Field

Let me now show you how to create one and display it in a post, if the key has a value.

Let’s say you want to tell people the mood you are feeling while writing the post, i.e. sad, angry, happy, etc…

We have to create the custom field for the post. To do this, open a previous post you create or create a new one and scroll down to “Custom Fields” box. If the Custom fields box does not exist, add it by enabling it in the Screen Options tab located at the top right of the post page.

Enter “Mood” as Name and enter a Value of whatever you want. For this example I’ll use “Happy” as the Value. Now press “Add Custom Field” after you are done.

Add Post Custom Field in WordPress

Create the Code Snippet

Now open your post template file, most likely single.php. Now we’ll display the post custom field, if a value exists, using a PHP code snippet. Put the code snippet where you want the custom field displayed.

 <?php $key = 'Mood'; $themeta = get_post_meta($post->ID, $key, TRUE); global $wp_query; $postid = $wp_query->post->ID; if($themeta != '') { echo '<strong>' . $key . ':</strong> '; echo get_post_meta($postid, $key, true); } wp_reset_query(); ?>

The result would be:

Mood: Happy

If the value of the custom field is empty, nothing will be displayed.

Customization

Customizing the above code snippet is easy. We’ll look at three (3) lines to do this: lines 2, 7 and 8.

On line 2, I have set a variable called key or $key. In the example, I used Mood as the key. Change $key value, which is “Mood” to whatever you have assigned the custom field “Name” to.

In the code snippet, the output is defined in lines 7 and 8.

To display the key name, which is the value of $key, use the following:

echo $key;

In the code snippet I’ve provided, the key will be in bold. You don’t have to bold the key – wrap the key with any HTML tags you want or simply just don’t show it; it’s up to you.

To display the information of the key, use the following:

echo get_post_meta($postid, $key, true);