11

I think it must be pretty basic question but I am only starting. Can someone have a look at the 3 versions of the same (?) code below and say what the difference is? All of them seem to work fine in the loop I am working on.

Which should be used: $post->ID, $the_ID or get_the_id()? Is it necessary to have global $post;?

global $post;
$content = get_post_meta( $post->ID, ‘my_custom_field', true );
echo  $content;

or

$content = get_post_meta( $the_ID, ‘my_custom_field', true );
echo  $content;

or

$content = get_post_meta( get_the_id(), ‘my_custom_field’, true );
echo  $content;

Many thanks for your help

Machavity
  • 30,841
  • 27
  • 92
  • 100
TheElear
  • 113
  • 1
  • 5

1 Answers1

10

If you're inside a WordPress loop, then $post->ID it's the same as using get_the_ID()

You shouldn't need to globalize $post since it's already in the scope of a WordPress loop.

I've never seen code using $the_ID, so I would avoid using that.

The safest choice would be to use get_the_ID()

felipelavinz
  • 549
  • 3
  • 6
  • Thanks felipelavinz for a prompt and informative answer. Make sense to me. It is my bad with the $the_ID as I think I did see the_ID() and not $the_ID. Having said that the code above works fine with it? – TheElear Nov 19 '14 at 13:03
  • 1
    Nope, `the_ID()` echoes the $post->ID so it wouldn't work when using `get_post_meta()` – felipelavinz Nov 19 '14 at 19:48
  • You are correct. I double checked and it does not work with the_ID(). – TheElear Nov 25 '14 at 10:36