Using Custom WordPress Fields To Add Meta Data

One nifty feature of WordPress is the ability to add custom fields which can be used to attach meta data to a post with or without the use of an extra plugin. You can add information like “my mood:” “currently listening too:” or heck, with some extra code you can make a post automatically expire.

To access the custom fields section first goto the “write post” page and scroll to the bottom. Once there click on the plus next to “Custom Fields”. It should look a bit like this:

Custom Fields for WordPress

The first chunk of information that needs to be entered is the meta data key, which is a unique identifier for the data. For example, you could enter “my_current_mood” as a key. The next field is for the actual data, this could be something like “Happy,” “Sad” or “Running in A Circle” - whatever best suits your purpose. Now click save.

The meta data you entered is now saved for that specific post and can be accessed with some minor template tweaking. You could also make a plugin to read in the data, but that is an entirely different topic.

Alright, so the meta data is saved and now you need to display it. This can be done using the built-in WordPress function “get_post_meta()”. Below is a quick explanation of each argument for the function:

get_post_meta($post_id, $key, $single);

$post_id - The ID of the post that you want the meta data for. 99% of the time this will probably be “$post->ID” which will get the current post’s ID.

$key - The unique identifier for the meta data you want, for example “my_mood”

$single - If set to true then a single chunk of data will be returned in a non-array format, if this is false then an array containing all of the values for the requested unique identifier will be returned. 99% of the time this will be set to “true”

To display the data simply insert get_post_meta with the proper arguments, then print out the data where you want it on your template (note: You should put it in The Loop). Here is a quick example of its usage:


<?php
$mood = get_post_meta($post->ID, 'my_mood', true);

print('Current Mood:' . $mood);
?>

Which would display something along the lines of:

Current Mood: Happy

There is a bit of a problem with this code, because it will display the text “Current Mood” even if no mood is set. So let’s fix that real quick:


<?php
$mood = get_post_meta($post->ID, "my_mood", true);
					
if(!empty($mood)) { 
print('Current Mood:' . $mood);
}
?>

The if statement will check to see if $mood has a value, and if it does it will print it all out. If it is empty then nothing will be printed.

So that’s it, enjoy :)

Please subscribe, or else I will cry. Do you really want to make a programmer cry?

Leave a Reply

Note: By submitting your comment you agree to this blog's comment policy.

If you want a little icon next to your name - sign up for one at Gravatar.