DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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!


  1. Hi,

    is there any way to get this function tweaked so that one can also access to custom field values within the functions.php itself?
    It seems that there id no $post->ID available in the functions.php.

  2. THANKS. This is just the trick I needed today.

  3. make $post as global in function.php

    eg – global $post;

Leave a Comment

Your email address will not be published. Required fields are marked *