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!

3 Responses

Feb 23 2012 08:01

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.

Apr 24 2012 17:42

THANKS. This is just the trick I needed today.

Apr 11 2013 11:31

make $post as global in function.php

eg – global $post;

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required

WP Theme of the week

Sponsored Likebox