get_post_meta Does Not Work Within The Loop

UPDATE: Please disregard this blog post. Ryan Duff gave me a huge tip that my code was not written correctly. In the code below, note that I have the line written as follows:
get_post_meta(post->ID, ‘custom_field_value’, true);
When you add the fancy dollar sign in front of “post->ID” like so “$post->ID”, the problem is fixed. Chalk it up to a late night bonehead move on my part, I guess. 🙂

I ran into a problem this morning.

I was trying to use get_post_meta() within the loop and was unable to return the custom field value.  The solution was to use “get_the_id()” rather than “post->ID” as shown below.

 

$my_query = new WP_Query('showposts=1');
	while ($my_query->have_posts()) : $my_query->the_post();
		get_post_meta(get_the_id(), 'custom_field_value', true);  // This works!
		get_post_meta(post->ID, 'custom_field_value', true);  // This DOES NOT work!
	endwhile;

Thanks to this post for providing the solution.

Posted in ,

Toby Cryns

Toby Cryns is a freelance CTO, expert WordPress developer, and teacher.

He offers free advice to improve your freelance biz.

He also publishes small droppings every now and them to https://twitter.com/tobycryns and https://twitter.com/themightymo.com

Follow Toby's contributions on Github and WP.org.