An Easy Way To Get the Contents of a Custom Field

October 9th, 2008 Nathan Rice

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.

Similar Posts:

The Tags: , ,

41 Responses to “An Easy Way To Get the Contents of a Custom Field”

Pangeran | PANGERAN.ORG Said:

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…

Comment made on October 9th, 2008 at 11:18 am
John Joubert Said:

Very nice article! *Bookmarked* Enough said :)

Comment made on October 10th, 2008 at 1:22 am
Magnus Jepson Said:

This is excellent stuff!

Comment made on October 10th, 2008 at 2:38 am
Mark Darling Said:

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.

Comment made on October 10th, 2008 at 3:12 am
Esther Said:

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!)

Comment made on October 10th, 2008 at 10:17 am
Nathan Rice Said:

@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!

Comment made on October 10th, 2008 at 10:29 am
erica stjohn Said:

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!

Comment made on October 13th, 2008 at 2:27 am
Jesse Sutherland Said:

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.

Comment made on October 13th, 2008 at 9:14 am
Nathan Rice Said:

@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.

Comment made on October 13th, 2008 at 9:43 am
Otto Said:

Why not just use the get_post_custom_values function?

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

Comment made on October 13th, 2008 at 1:08 pm
Nathan Rice Said:

@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.

Comment made on October 13th, 2008 at 1:15 pm
Otto Said:

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).

Comment made on October 13th, 2008 at 3:34 pm
Nathan Rice Said:

@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.

Comment made on October 13th, 2008 at 3:47 pm
amit Said:

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. :)

Comment made on October 14th, 2008 at 1:28 am
Nathan Rice Said:

@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.

Comment made on October 14th, 2008 at 9:35 am
amit Said:

@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! :)

Comment made on October 14th, 2008 at 2:36 pm
Nathan Rice Said:

@amit:
Glad to hear it! :-)

Comment made on October 14th, 2008 at 4:55 pm
Michiel van der Blonk Said:

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

Comment made on October 15th, 2008 at 10:05 am
Nathan Rice Said:

@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.

Comment made on October 15th, 2008 at 10:12 am
Stephen R Said:

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'); ?>

Comment made on October 18th, 2008 at 12:06 pm
Nathan Rice Said:

@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.

Comment made on October 18th, 2008 at 12:10 pm
Albert Said:

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

Comment made on November 10th, 2008 at 9:22 am
Nathan Rice Said:

@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

Comment made on November 11th, 2008 at 10:56 am
Albert Said:

Can you give some example??

I’m totally lost.

Thanks!!

Comment made on November 11th, 2008 at 3:17 pm
Nathan Rice Said:

@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.

Comment made on November 11th, 2008 at 10:59 pm
Albert Said:

Ok, there’s no problem.

Thank you for your time.

Comment made on November 12th, 2008 at 3:26 am
Sarah Said:

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

Comment made on November 13th, 2008 at 11:46 am

Trackbacks

An Easy Way To Get the Contents of a Custom Field — WPCandy — WordPress Themes, Plugins, Tips, and Tricks Said:

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

Comment made on October 9th, 2008 at 8:11 pm
Custom Fields Made Easy | Wordpress Blog NL Said:

[...] 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 [...]

Comment made on October 12th, 2008 at 6:08 pm
WordPress | Cara mudah mengambil content sebuah Custom Field | display:inline Said:

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

Comment made on October 12th, 2008 at 9:30 pm
links for 2008-10-13 Said:

[...] 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 [...]

Comment made on October 13th, 2008 at 8:01 am
links for 2008-10-13 | Deuts’ Notepad Said:

[...] 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. [...]

Comment made on October 13th, 2008 at 9:00 am
Links for 2008-10-13 - chrishubbs.com Said:

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

Comment made on October 13th, 2008 at 10:01 am
Custom Fields Made Easy | PATRON DIGITAL.COM Said:

[...] 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 [...]

Comment made on October 13th, 2008 at 12:08 pm
Links for 13th October 2008 | Velcro City Tourist Board Said:

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

Comment made on October 13th, 2008 at 8:01 pm
Custom Fields in Wordpress Pages… the Easy Way « Coder Dan Said:

[...] 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 [...]

Comment made on October 15th, 2008 at 11:22 pm
Linkdump for October 16th at found_drama Said:

[...] 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… [...]

Comment made on October 16th, 2008 at 8:00 am
An Easy Way To Get the Contents of a Custom Field :: Nathan Rice | clhmedia.com Said:

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

Comment made on October 20th, 2008 at 7:19 am
Custom Fields Made Easy | BlogBroker24-7 Said:

[...] 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 [...]

Comment made on October 22nd, 2008 at 9:54 am
Weblog Tools Collection: Custom Fields Made Easy | Aslifmbiz Blog Said:

[...] 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 [...]

Comment made on October 23rd, 2008 at 11:40 am
Feed Subscriptions, Stats and Management « Feet up, eyes closed, head back Said:

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

Comment made on November 15th, 2008 at 4:53 pm
 

Leave a Comment