Get Custom Field Fail

This is a bit of a head scratcher. It’s one of those that makes you wonder what the original developer was thinking, and not because it does something really poorly but because it does something that is completely pointless.

// Get custom field value.
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;
}

The function does nearly exactly the same thing as get_post_meta(), which is what the function is using to retrieve the custom field.

The only thing this does (perhaps) better than get_post_meta() is have the $echo parameter to let the user set whether the function should return or echo the value.

One this thing function fails on (aside from doing something generally pointless) is not provide a way to specify the post ID, meaning that this function will only work accurately inside of the loop.

How should this be done instead? This:

echo get_post_meta( $post->ID, 'custom_field', true );

Submitted by Drew Jaynes.

Advertisements

9 thoughts on “Get Custom Field Fail

  1. Obvious typo in improved code…. (GT conversion)

    echo get_post_meta( $post->ID, ‘customer_field’, true );

    should be…

    echo get_post_meta( $post->ID, ‘customer_field’, true );

  2. The only thing this function has going for it is that it uses the current post ID when in the loop. It could be an optional parameter, replacing the echo because that’s four letters better placed in the front of the function call for readability anyway, especially when it returns by defaut anyway (like get_post_meta)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s