get_the_id vs. post->ID vs. the_id / get_post_meta

Deadly 提交于 2019-12-04 20:17:13

问题


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


回答1:


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()



来源:https://stackoverflow.com/questions/26978722/get-the-id-vs-post-id-vs-the-id-get-post-meta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!