0

On a category archive page, in a filter called from a block outside a loop, I noticed that the get_post function with a null first parameter returns the first loop's post.

Is it supposed to return such a value ? I would have imagined that the global $post variable should have a value only in a loop or on a post page.

1
  • Can you add your code snippet here please Apr 15 at 11:51

1 Answer 1

1

Yes, this is how it is supposed to work. The global $post variable is set quite early in the page load, at the wp hook. As you can see from the hook order, this is before the loop starts.

Basically the $post object exists independent from its actual content in the database, which you retrieve during the loop. It's specifically meant to be accessible all the time during page generation.

9
  • What value is it supposed to have if it doesn't get its content from the database ? In my case it seems to still have a peek into the loop to retrieve its first item.
    – challet
    Apr 15 at 13:52
  • 1
    It's a bit like Schrödinger's cat: it doesn't have a value until you open it. The loop is the normal way to open, but you can access it anywhere on the page. get_post will give you the first post of the query and get_posts all of them.
    – cjbj
    Apr 16 at 8:47
  • So, it is related to the database content
    – challet
    Apr 23 at 23:32
  • No, not really. If you approach a website, WordPress first looks at the url. This translates into a query (a post, page, category archive, and so on). That's where the global $post variable is created. Next there are filters that may change the query (for instance amount of posts on a specific category archive page). Only when all this is done the query is actually executed and content is derived from the database.
    – cjbj
    Apr 24 at 9:31
  • I'm sorry, I'm confused. What do you mean not really ? And what value is it supposed to have other than null (or false, or anything that can be tested as not initialized) or a database record ? Of course a variable has no content before it exists. But my question is about that variable value in a block template but before the loop happens.
    – challet
    Apr 24 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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