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

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.

Reader Interactions


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

  3. 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 — consider my subscribed!)

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

    Hopefully, it turns out to be useful for you!

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

    Glad it helped!

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

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

  7. Why not just use the get_post_custom_values function?

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

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

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

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

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

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

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

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

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

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

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


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

  17. 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?

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

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

    thanks in advance.