'Could anyone tell me why my function works in index.php but not in functions.php?

I'm new to stackoverflow and PHP so please bare with me :) I'm having a problem with displaying correct information on my WordPress site and I'm not sure why. I have written this function that is in functions.php:

function my_page_id(){  
  $page_id = get_queried_object_id();
  echo "Page ID = " . esc_html($page_id);
}
add_action('init', 'my_page_id');

This displays

"Page ID = 0" 

However, when I call the function directly in one of my other files such as index.php:

my_page_id();

It displays:

"Page ID = (correct ID number)" 

Could anyone tell me why??

Thanks in advance, Matt

php


Solution 1:[1]

The currently_queried_object is the object that is subject of the webpage.

So on a category archive or tag archive page it will return the WP_Term object of that page. On any singular page (a single post, a single page, or a post in a custom post type), it will return the WP_Post object of that post or page.

So, if you use the function in your functions.php there is no currently_queried_object and therefore the id is 0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 geertjanknapen