How to: Easily get the value of a custom field

December 3, 2008 at 8:53 am

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!