How to: Easily get the value of a custom field

Nowadays, most modern WordPress themes uses custom fields, to display a thumbnail near the post excerpt, or for adding any other kind of data. Here’s a custom function, created by Matt Varone, to easily get any custom field value.

Here's the function. You have to paste it on your theme functions.php file. If your theme doesn't have a file named functions.php, create one.

function get_custom_field_value($szKey, $bPrint = false) {
	global $post;
	$szValue = get_post_meta($post->ID, $szKey, true);
	if ( $bPrint == false ) return $szValue; else echo $szValue;
}

Now, to call the function and get your custom field value, use the following code:

<?php if ( function_exists('get_custom_field_value') ){
        get_custom_field_value('featured_image', true);
} ?>

First, we use the php function_exists() function to make sure the get_custom_field_value function is defined on our theme. If it is, we use it. The first argument is the custom field name (here, featured_image) and the second let you echo the value (true) or get it for further use in php (false).

Thanks to Matt Varone for this awesome piece of code!

22 Responses

Dec 03 2008 13:26

Really usefull ! Thanks for the tips ;)

Dec 04 2008 00:41

bounced over from smashing mag - good stuff - keep cooking..

Dec 04 2008 00:47

Thank you guys!

Dec 04 2008 01:22

Thank for this! I have always wondered how people add custom fields to their themes

Dec 04 2008 05:22

As usual great code, Jean. Please correct me if I’m wrong, the only element I need to change is ‘featured_image’ if I were to use say, ‘thumbnail’….is that right?

Yan

Dec 04 2008 08:12

@Blog for beginners: Exactly, just change “featured_image” by he name of you custom field :)

Dec 04 2008 08:14

Thanks for the clarification, Jean.

Yan

Dec 04 2008 11:08

You’re welcome :)

Dec 07 2008 13:01

Again very nice recipe, I’ll try to make use of this in soon time after I got a permanent theme for my blog and for my other blog, it can help out adding some special details on selected posts etc etc.

Dec 11 2008 23:50

Do you need to put it in the loop?

Dec 12 2008 00:15

@Ninon: Yes.

Dec 12 2008 06:08

This is a very important tip. It can make WP much more powerful and flexible with Custom Fields to display anywhere you want. Very good. Thank you again. I already have this working before this post but I like to see more discussion of techniques for using this.

Jan 04 2009 17:13

Very useful, and I’m using it!

One question though.. I’m using it to show dates of tours/trips. Some trips have more than one date custom field associated with them (date1, date2, date3, etc). How could I test for a non-empty custom field? In other words:

Show date1
If not empty show date2
If not empty show date3

Gary

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required
Blog And Make Cash