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.
Enjoy this article?
Donate
Me on tumblr
- Diberi Soal "Bonus", Malah Curiga
- NASA Space Orbiter For FREE!
- sudo make me a website (around 1:10) :))
- Color Scheme Designer
- When the worlds collide!
- "Buat apa ngoceh Pesta Blogger segala, kalau blognya tidak pernah di update. Buat apa..."
- Twitter Myths
- Duh Emen, Jadoel nian engkau ini Emen…
- "what programming is: mathematics or engineering? Craft, art, or science?"
- Makanan Perusak Diet!
Me on posterous
About Me
Hi, I'm Arief. Currently, I worked with Indonesian biggest entertainment website. I also did some freelance job. You got something for me? You can contact me here. For a complete info, head over here and here.
All text written here is copyrighted their rightful owner. If it's mine and no other copyright information on that particular page / post. Then, it's licensed WTFPL






March 21st, 2010 - 13:20
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 ?
March 21st, 2010 - 13:52
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.
March 21st, 2010 - 13:53
Here's a reference for you:
http://www.binarymoon.co.uk/2007/05/wordpress-t...
March 21st, 2010 - 14:17
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 ?
April 3rd, 2010 - 08:37
Nice share. I had same problem and this also is a good help. Thank you.