Why isn't get_post_meta working?

dmanexe picture dmanexe · Nov 16, 2010 · Viewed 18.4k times · Source

Simple Wordpress problem - get_post_meta is not retrieving custom field values. Here's the code that is pulling from the custom fields:

<img src="<?php echo FCG_PLUGIN_URL; ?>/scripts/timthumb.php?src=<?php echo get_post_meta($post->ID, 'slider_image', true); ?>&h=250&w=400&zc=1" alt="<?php echo $post_title; ?>" />

In production, this is the HTML I get:

<img alt="Post Title" src="http://***.com/wp-content/plugins/jquery-slider-for-featured-content/scripts/timthumb.php?src=/&amp;h=50&amp;w=80&amp;zc=1">

You can see the src= point in the string is empty - as if there is nothing posting from it. I have isolated and echo'd just the get_post_meta and it's a whitespace. I am 100% sure it's named correctly within the post - is there something glaring I'm missing here?

Answer

Katie picture Katie · May 24, 2011

If you are calling get_post_meta inside the loop then you should call get_post_meta(get_the_id(), 'YOURKEY', true) instead of get_post_meta($post->ID, 'YOURKEY', true)

Strange things happens when you call get_post_meta inside a loop. In some themes developers hack the $post at the beginning and get_post_meta stops working so this is one of the solution for those particular cases too.