Freelancer's Playground! New knowledges every now and then

3Nov/095

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.

10 Most Popular Search Terms

  • uwiuw

    interesting. but i'm still 'mudeng'. care to explain more with sample case or scenario where this wrapping wp built-in function should be create ?

  • http://bayu.freelancer.web.id/ ariefbayu

    I wonder, did you read that post properly? it's written there:
    For your convenience, save it in functions.php under your theme directory.
    If you don't have this file, you can create it first and if you don't know where is your theme directory, it's in: /wp-content/themes/whateverthemeyouuse/

    Hope that helped.

  • http://bayu.freelancer.web.id/ ariefbayu
  • uwiuw

    i'm sorry my hand in the keyboard but my mind is somewhere else. What i want to ask is not where but why ? so…please explain more ;D, do you mind ?

  • http://www.chipmagician.com/ auto body lexington

    Nice share. I had same problem and this also is a good help. Thank you.