Question

Inside my functions.php I use get_post() or similar (such as get_the_title()) inside some of my functions. It does not return anything. Why? And how to fix that?

P.S: And I can not really add add_action('somehook', 'myfunc'), because that makes things display in the wrong place.

Was it helpful?

Solution

When $post is null for get_post it looks to $GLOBALS['post'].

There are several other checks in the source so perhaps you should find out the value of the global variable when you're calling it or give it something besides and empty value.

What does get_the_id() return vs. get_post(get_queried_object_id())? Or var_dump(get_queried_object())?

get_post() - Retrieves post data given a post ID or post object.

get_queried_object() - Retrieve the currently-queried object. For example:

  • if you're on a single post, it will return the post object
  • if you're on a page, it will return the page object
  • if you're on an archive page, it will return the post type object
  • if you're on a category archive, it will return the category object
  • if you're on an author archive, it will return the author object etc.
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top