I am confusing to use $post
global variable. Is it use inside loop or outside loop? What is the advantage to use it inside and outside loop?
2 Answers
The $post
global is set by $wp_query->the_post()
. As $post
is set by the main query and the fact that templates are set within the global variable scope, it is available throughout the template, so there is no need to explicitly calling the $post
global when you are within the specified template as the WP_Post
objects can be accessed any where. You can access the WP_Post
objects by just simply calling them directly, for example $post->ID
to retrieve the page ID on a page template
When you need to access post data outside of a template, for example, in a function or in a widget, you need to call the $post
global to make the post data available for use.