phpwordpress

What's the difference between global var post and get_post?


I use the_posts filter to add an object to each queried post. When access the added object, I get different result by using $post or get_post.
This is the code to attach the object to posts:

add_filter( 'the_posts', 'populate_posts_obj', 10,2 );
function populate_posts_obj( $posts, $query ){
  if ( !count( $posts ) ||  !isset($query->query['post_type']) )
    return $posts;
  if( in_array( $query->query['post_type'], get_valid_grade_types())){
      foreach ( $posts as $post ) {
         if (  $obj = new Gradebook( $post->ID ) )
            $post->gradebook = $obj;
      }
   }
  return $posts;
}

Then, access the obj via $post, sometimes get the obj, sometimes not (even when it's the same post):

function get_the_gradebook(){
  global $post;
  return isset($post->gradebook) ? $post->gradebook : null;
}

Access the obj via get_post(), always get the obj:

function get_the_gradebook(){
global $post;
  $p = get_post($post->ID);
  return isset($p->gradebook) ? $p->gradebook : null;
}

I can just use the get_post() version, but it would be useful if I know why the difference.

Additional info:

If you ask the reason I attach an obj to each post, I think WordPress may take care of the caching process at the first place. Then, other caching plugins can work on my obj as if working on standard WP posts.


Solution

  • Lets explain you with a little bit pseudo code. I am trying to be broad with my approach so that my answer is relevant to StackOverflow however I still don't know how many down votes I may be receiving for this.

    The simple difference is $post is a variable and get_post() is a method that means you can expect a different output from get_post() due to several dependencies however $post will only change when you explicitly do that.

    Lets assume something like this

    function get_post() {
        return rand(0, 5);
    }
    
    $post = get_post(); /* lets assume random 
                           value that was generated 
                           this time was "2" */
    

    Now each time you call get_post() its value be keep changing however the value of $post is always 2.

    Coming back to the context of wordpress, $post is set using get_post() within the Loop and corresponds to the object referring to default post ID for current URL where as get_post() will take post ID as an input and return the post object.