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.
function get_custom_field($post_id, $custom_field, $echo = true) {
$meta = get_post_meta($post_id, $custom_field, true);
if($echo){
echo $meta;
}else{
return $meta;
}
}
better?
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 );
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)
Fixed, thanks!
Won’t it also throw an unidentified index notice if echo is true and there isn’t a value to be echoed?
No, because the $echo parameter is still defined, just not set to false.
get_post_meta always returns an empty string if a key isn’t found; At worst, you’d get “Array” back.
Shouldn’t it also be “custom_field” instead of “customer_field”?
That was just an example meta field key, but yet, that was a typo đŸ™‚