Get WordPress Post ID Outside the Loop

It is easy to get a post ID in WordPress. To echo it on screen we write:

 <?php the_ID(); ?>

To store the ID into variable we use something like this :

 $id = get_the_ID();

There is one caveat though: if you read the description on WordPress codex it says this in both cases: This tag must be within The Loop.

So if you ever wanted to retrieve or display the WordPress post ID in footer or header or outside of The Loop you might end up being disappointed because the ID returned is not the correct one (usually we always get the same id, most probably the last one?)

Now I am not going to go into technical details or why is that so here is the solution that worked for me. You

$post = $wp_query->post;
echo $post->ID;

There are some other ways with global variables and some other but it seem it doesn’t work for everyone. This one worked on the first try. Let me know in comments if it doesn’t work for you.