1

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?

1

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 functions wp_reset_query and wp_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:

$recent = get_posts(/*...*/);
foreach ($recent as $r) {
  the_title();
}

And you need:

$recent = new WP_Query(/*...*/);
if ($recent->have_posts()) {
  while($recent->have_posts()) {
    $recent->the_post();
    the_title();
  }
}
wp_reset_postdata();
2

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.

  • Very nice Q&A, but right now I'm curious to know, how do we get the current post? – brasofilo Oct 19 '13 at 6:03
  • @brasofilo - you know this probably better than I do, but I would presume that you know you could / should use get_the_ID(), get_post(), and other functions that are built into WP. – cale_b Oct 19 '13 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.