An Easy Way To Get the Contents of a Custom Field

If you do any hardcore WordPress coding, then you’re probably aware of Custom Fields and the unlimited possibilities they offer you as a WordPress designer or developer.  For instance, I use custom fields as a means of attaching a feature image and thumbnail to posts in my Proximity News Theme.

But, they can be a bit cumbersome to use throughout your theme because of the ridiculous amount of code that it takes just to pull the data out and display it.

Conventionally, here’s how you would pull the data from a custom field where the key = image and use the value of that field as the “src” value in an IMG tag:

<?php $image = get_post_meta($post->ID, 'image', TRUE); ?>
<?php if($image) { ?><img src="<?php echo $image; ?>" alt="Alt Text" /><?php } ?>

Putting the value from the custom field into a variable definitely cuts down on the amount of code you have to write, but by utilizing a simple PHP function, we can make using custom fields even easier!  Open up your theme’s functions.php file and paste the following code somewhere between PHP tags:

function get_custom_field($key, $echo = FALSE) {
	global $post;
	$custom_field = get_post_meta($post->ID, $key, true);
	if ($echo == FALSE) return $custom_field;
	echo $custom_field;
}

Now, when you want to get the value of the custom field, you simply use the function in your theme files like so:

<?php get_custom_field('image', TRUE); ?>

Using the “TRUE” value makes sure that the function actually echos the value, rather than just returning it.  But if for some reason, you need to use the value of the custom field (for instance, to store in a variable), then you can return the value instead of echoing it like so:

<?php get_custom_field('image', FALSE); ?>

Also, you could change the value of the $echo varialble in the function declaration to TRUE if you would like the default for the function to be to echo the value, rather than return it. It’s really up to your preferences.

Now, let’s take it one step further.  Let’s recycle some code from our get_custom_field function and use it in a function that will check to see if that custom field has a value — and if it does, then to use that value, along with the proper IMG tags to output an image, including width and height specifications:

function image_attachment($key, $width, $height) {
	global $post;
	$custom_field = get_post_meta($post->ID, $key, true);

	if($custom_field) { //if the user set a custom field
		echo '<img src="'.$custom_field.'" alt="" width="'.$width.'" height="'.$height.'"/>';
	}
	else { //else, return
		return;
	}
}

Then, just use the function in your theme files.  This example would echo the image with a width and height of 100px:

<?php image_attachment('image', 100, 100); ?>

Cool, huh? 🙂  Feel free to experiment with the many, many opportunities these kinds of shortcuts can bring you.

51 Replies to “An Easy Way To Get the Contents of a Custom Field”

  1. I just use this.

    [?php $image = get_post_meta($post->ID, ‘feature image’, true); ?]

    [img src=”[?php echo $image; ?]” alt=”Feature” /]

    For call up an imgage using custom field… For example in homepage?

    Also can be use to embed video…

  2. […] Nathan Rice explains how to use a quick PHP function to get data from a custom field. [Link] […]

  3. Very nice article! *Bookmarked* Enough said 🙂

  4. This is excellent stuff!

  5. I wrote an article myself recently about accessing custom fields but this is a much neater way of doing it, I may post an update to my article pointing at this.

    Cheers, Mark.

  6. I was planning on using a custom field in a new theme and was unsure where to start — this came at a perfect time. Thank you! (Found this post via WPCandy.com — consider my subscribed!)

  7. @John Joubert:
    Thanks! Glad you liked it!

    @Mangus:
    Hopefully, it turns out to be useful for you!

    @Mark:
    That was really my goal. I figured a simple function with a single variable input would be the easiest way to get it done.

    @Esther:
    Glad it helped!

  8. […] Rice who is a prominent theme author within the WordPress community has published an article that explains an easy way to retrieve the contents of a custom field. Instead of doing things the […]

  9. […] Nathan Rice membagi tips mengenai cara mudah untuk mengambil content dari sebuah Custom Fields. […]

  10. I just found this via http://weblogtoolscollection.com/archives/2008/10/12/custom-fields-made-easy/

    Very nice article! Thanks so much for showing a simple and easy way to do this!

  11. […] An Easy Way To Get the Contents of a Custom Field :: Nathan Rice (tags: wordpress php) This entry was posted in links. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL. « links for 2008-10-11 […]

  12. […] An Easy Way To Get the Contents of a Custom Field If you do any hardcore WordPress coding, then you’re probably aware of Custom Fields and the unlimited possibilities they offer you as a WordPress designer or developer. For instance, I use custom fields as a means of attaching a feature image and thumbn (tags: wordpress wordpress_design custom_fields wp_design obeertym) var disqus_url = ‘http://notepad.deuts.net/archives/305 ‘; var disqus_title = ‘links for 2008-10-13’; var disqus_message = ‘%0AAn Easy Way To Get the Contents of a Custom Field%0AIf you do any hardcore WordPress coding, then you’re probably aware of Custom Fields and the unlimited possibilities they offer you as a WordPress designer or developer. For instance, I use custom fields as a means of attaching a feature image and thumbn%0A(tags: wordpress […]%0A’; View the entire comment thread. […]

  13. Isn’t one of the benefits of using code like this instead of the default code because then it can be used outside of the loop? I was really annoyed for a long time that I couldn’t use custom fields outside of the loop, and no one ever seemed to talk about that limitation! I eventually found a plugin that helped me, but would this code do it by itself?

    If this is true, you should add it to your post. I’m sure that tidbit would be helpful to many.

  14. @Jesse Sutherland:
    I don’t believe you can use this function outside the loop as it currently stands. In order to do that, you’ll have to globalize the $wp_query variable instead of the $post variable, then define the $post variable as $post = $wp_query->get_queried_object();

    I haven’t tested that, but I believe if you do that within the function, you’ll be able to use the custom field outside the loop.

  15. […] An Easy Way To Get the Contents of a Custom Field :: Nathan Rice (tags: wordpress tips ) […]

  16. […] Rice who is a prominent theme author within the WordPress community has published an article that explains an easy way to retrieve the contents of a custom field. Instead of doing things the […]

  17. Why not just use the get_post_custom_values function?

    $imagearray = get_post_custom_values(‘image’);
    echo $imagearray[0];

  18. @Otto
    I find that this function (and variations of it) gives much more flexibility, and can cut down on number of lines used in the theme itself.

    So, instead of having to echo the value manually, you can just set the second parameter to TRUE.

    Really, the power of this function is in it’s variations, like the example of displaying an image. So, instead of just the “else return;”, we could easily set the function to fall back on an image in the gallery, or a default image in the /images folder.

  19. Yeah, I get that, but I’m just wondering why use get_post_meta (which is not a Loop function) instead of get_post_custom* (which are Loop functions and thus don’t require specifying the ID of the current post).

  20. @Otto:

    You make a compelling point. I suppose either is fine. Since either one can specify a post ID, it doesn’t look like there is much benefit of one over the other. what room you save by not having to use $post->ID you lost by having to use [0] in the places the variable is used.

    Either/Or, I guess.

  21. […] An Easy Way To Get the Contents of a Custom Field […]

  22. Nathan, I don’t see the logic of writing the extra lines in the function “get_custom_field” when all you need to do is:

    echo get_post_meta($post->ID, $key, true);

    to print out the values of custom field directly in the theme & when it needs to be put in a variable then all it needs is just:

    $my_variable = get_post_meta($post->ID, $key, true);

    If you are gonna print out the custom field then you are writing “get_custom_field” anyways with an additional parameter, better just write “echo”. And when the custom function is being used to return a value then the variable is being written as well to put the returned value in. So essentially, the code of the custom function is not benefiting anything but just adding more lines for PHP to parse!!

    Sorry, but I don’t see any sense in this, looks more like bloating the code! Bad example in this case I guess. 🙂 Other than that, that image calling function is good, reduces the amount of code overall and makes it easier to maintain. 🙂

  23. @amit:
    Because the get_post_meta function is a return function, and won’t echo on its own. And by using the external function (assuming you’re going to use custom fields more than once in your template), you actually reduce the overall code.

    But like I said, the real value to this function is in its variants. You can seriously reduce code by using the core of this function to do bigger things.

  24. @Nathan

    But like I said, the real value to this function is in its variants. You can seriously reduce code by using the core of this function to do bigger things

    Yep I agree on that as I use it myself! 🙂

  25. @amit:
    Glad to hear it! 🙂

  26. check out the enzymes plugin at http://noteslog.com/enzymes/. It can do all of this and a lot more.

  27. @Michiel van der Blonk:
    The whole point is to get people to understand things like this, so they can start building their own stuff. Yes, there’s probably a plugin for everything. But you might notice that I’m not in the habit of recommending plugins for functions that can be easily created and integrated into a theme.

  28. […] about custom fields is fairly vauge and not very easy to figure out. Nathan Rice over at (ironic) NathanRice.com has post some quick tips on how to quickly and easily setup custom fields for your page […]

  29. […] An Easy Way To Get the Contents of a Custom Field by Nathan Rice :: eventually I will need to learn what these Custom Fields are and what to do with them… […]

  30. Excellent article. I love stuff like this that makes a solid core for expansion… 🙂

    It should be pointed out — the way you wrote the function, there is no need to pass “false” if you’re returning the value. Just use this:

    <?php get_custom_field('image'); ?>

  31. @Stephen R:
    You’re absolutely right. You don’t have to use the FALSE at all. Most people don’t know enough about PHP to know that, so if I had left it out, I would have had a bunch of questions 🙂 So, I just went ahead and put it in.

    But yes, to anyone interested, you do not have to put the FALSE into the function call. Just do what @Stephen did in the comment above.

  32. […] Feed Item View This Article  Email This To A Friend   […]

  33. […] Rice who is a prominent theme author within the WordPress community has published an article that explains an easy way to retrieve the contents of a custom field. Instead of doing things the […]

  34. […] 2008 in wp-rss Nathan Rice who is a prominent theme author within the WordPress community has published an article that explains an easy way to retrieve the contents of a custom field. Instead of doing things the […]

  35. It’s possible do the same to show image custom field into RSS feed?

    1. @Albert,
      In order to do that, you’d need to filter the_content and add the custom field to it. It’s possible, but you’d need to be comfortable with using WordPress filters.

      Nathan

  36. Can you give some example??

    I’m totally lost.

    Thanks!!

    1. @Albert,
      That’s another post, for another day 🙂 I’m afraid a comment wouldn’t do the method justice, and I have a policy for introducing new concepts to readers in baby steps.

      Stay subscribed to the blog, and I promise you that I’ll write a post about filters soon, along with a follow-up post with practical applications.

  37. Ok, there’s no problem.

    Thank you for your time.

  38. Just found this and I think it’s great-just what I need.
    I also read what Steven R said:

    “It should be pointed out — the way you wrote the function, there is no need to pass “false” if you’re returning the value. Just use this:

    Being new to all this, how would the whole code look like then without the “false” there?
    Thanks

  39. […] An Easy Way To Get the Contents of a Custom Field from Nathan Rice […]

  40. can i use this with the featured content plugin to automatically display the images in the plugin? thanks!.

  41. What is the easier?

  42. Great Article, i’ve been looking for something like this for ages. One question though…
    Let’s say i wanted to pull 2 images, by having 2 custom fields under ‘image’. Is there something you can add to the code to pull both images?
    At the moment i can only pull 1 image, regardless of how many images i have specified in my ‘image’ custom field

  43. […] An Easy Way to Get the Contents of a Custom Field […]

  44. Nice approach…
    I did it a bit different. I wrote a plugin that creates a shortcode called “meta”. With it you can directly insert the custom fields contents into your articles – from within your article. The plugin can also be extended by writing php code or even in the admin area. For more info visit http://www.matthiasamacher.ch/wordpress/meta-functions-shortcode. The plugin is also hosted on wordpress.org

  45. how can i do this to embed a video from youtube or vimeo with defined value for width and height?

    thanks in advance.

  46. […] An Easy Way To Get the Contents of a Custom Field […]

Comments are closed.