I am a newbie at WordPress. In my “recent posts” shortcode, I used global $post
variable, because the_title()
function was giving me page’s title, not post’s title. I am not exactly sure, but I thought that’s because of loop inside of a loop.
Some advanced users here tell me not to use global
variable, so using global $post
variable inside my “recent posts” shortcode is good or not?
The
global
variable$post
will be set to the first post in the main query. When any Loop runs (assuming it is constructed correctly), whether the main Loop or any number of secondary ones,$post
will be set to each post in that/those loops in turn. At the end of the Loop, it will be set to the the last post in the last Loop that ran. The functionswp_reset_query
andwp_rest_postdata
help clear this up in a lot of cases.I am pretty sure that the problem is the construction of your “loop inside of a loop” but you don’t post the code so guessing is all I can do. My guess is that you have something like:
And you need:
The disadvantage is that
global $post
can give you unexpected results, unless you are confident you are inside the loop.Widgets and other plugins can rewind your posts, loop through post to a different position, and other actions that could cause you to get results that you did not want or expect.
Since you don’t tell us where your shortcode is getting executed, it is possible that it may be outside the loop, and could give unexpected results.
If your shortcode is supposed to list recent posts, then it is definitely not the right application of
global $post
– you need to investigate Writing a Custom Loop in order to get the recent posts, without affecting the main loop.