WordPress Hack #1: Global Meta Variable for Custom Fields

This is the first in what I hope will be a series of posts on “WordPress Hacks”, simple code you can add to functions.php to make your life as a developer a little easier.

Ever get tired of typing get_post_meta($post->ID, $meta_key, $true); to fetch even the simplest of WordPress custom field values. Try this.

add_action('the_post','setup_meta_var');
function setup_meta_var() {
global $wp_query,$meta;
$vals = get_post_custom($data->ID);
foreach($vals as $k => $v) 
{
if(count($v) > 1):
$meta[$k] = $v;
else:
$meta[$k] = $v[0];
endif;
}
}

What this dandy little function does is automatically assign a post or page’s custom values to a global variable call $meta.

To use your custom field values now, you simply have the do echo the meta_key like so:

global $meta;
echo $meta['meta_key'];

If there is more than one value for that custom field, you will simply need to do a standard foreach loop.

global $meta;
foreach($meta['meta_key'] as $m) {
echo $m;
}

Update: Hey, I realized that in the code snippet I pasted here I was setting a $type variable. That was a relic of the custom script this code was taken from … so please ignore.