Wrapping get_post_meta() with default value

As wordpress developer, we will almost always use get_post_meta(). There’s a catch in using it though, as there will be situation where we want to get a meta value on a non initialized meta. Something thing we expected to be present but not created yet.

To overcome that problem, I created another function that wrap get_post_meta(). I use get_post_meta_w_default() as new function’s name with method body:

function get_post_meta_w_default($post_id, $key, $single = false, $default = '')
{
    $value = get_post_meta($post_id, $key, $single);

    if(empty($value))
        $value = $default;

    return $value;
}

That’s is, all you have to do is just using it like this:

echo get_post_meta_w_default($post_id, 'image-post', true, 'http://alamatblog.com/images/no-image.jpg');

For your convenience, save it in functions.php under your theme directory.

blog comments powered by Disqus