Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Other Digging In To WordPress – Use of global keyword

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #32582
    gradyetc
    Member

    I’ve been reading (and thoroughly enjoying) “Digging in to WordPress v3.1” and I’ve come across a few examples that I don’t quite understand.

    Take the following example (p.92), which creates a second loop outside of the main loop using get_posts():

    
    global $post;
    $args = array('category' => -9); // exclude Asides category
    $custom_posts = get_posts($args);
    foreach($custom_posts as $post) : setup_postdata($post);
    ...
    endforeach;
    ?>

    What exactly is the purpose of including “global $post” at the top? If the foreach loop just extracts new posts from $custom_posts, isn’t that variable just overwritten anyways? I see that it is that way in the WP Codex as well, so I’m certain it is for a reason, just curious what it is.

    #47461
    shazdeh
    Member

    Does this actually work? PHP does not have block scope variable so $post in the foreach loop refers to the global $post variable which contains all posts that are currently being viewed.

    #47248
    gradyetc
    Member

    It does — global $post just contains the current post when it’s in the loop. And now that I say that, I’m wondering if it is there in this instance to emulate that behavior. In the loop, the global $post variable contains info for the current post, so when you create a manual loop using get_posts you follow that convention as well.

    At least that’s my best guess, seeing as I can’t see any reference to this behavior in the codex…

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘Other’ is closed to new topics and replies.