How to Retrieve Custom Post Meta Data in WordPress

by • On Nov 14, 12 22:40pm • 1098 Views

One of the reasons why I like WordPress so much is its flexibility. This simple CMS gives you so much space to play around that you literally do whatever you want. One such feature is the capability of adding “Custom Fields” to add Meta data with your posts. It can be used so many ways that it can boggle your mind.

WordPress Tips & TricksRecently, I was working on an entertainment related blog site where the authors wanted me to have the option to add album cover, genre, album release date, movie actors list, awards stuff like that with each post. So, I decided to use “Custom Fields” to add additional information which would be related with post type. Since they would be writing both music album and film reviews, I had to add the lots of Meta key/Name. Trust me, it was easy.

Adding data was the easiest part. However retrieving them wasn’t as easy as I thought. After doing some Google search, I came across the WordPress Codex page of Custom Fields and found the following piece of code. Which worked just fine without any extra headache.

<?php echo get_post_meta($post->ID, 'album_cover', true); ?>

Unfortunately, this code works only if you want to retrieve the meta data within The Loop. But our custom made theme had to display the meta data outside of the loop for the sake of the design itself. Now, before I proceed any further I want you to look at the screenshot given below for better understanding.
Custom Meta field in WordPressAs you can see here, we were using “album_cover” as the Meta key which will have a Meta value, in this case it is the image URL of an album cover.

After couple of minutes of testing, I came up with the following piece of code which can retrieve the Meta value outside of the loop. It worked like breeze.

<?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'album_cover', true);
?>

Next thing all I had to do is to add an Image Tag and put the above code as the value of “src” attribute, that’s all.

I hope, you would find this post helpful. Thank you.

You can follow us on Twitter, add on your Google+ circle or Like our Facebook page to get the latest news, updates and reviews.

advertisement

Comments