The best way to get ID of each WordPress page

I needed to get page ID in header.php for each page for my WordPress theme. There are more then one solutions for this, but the only one worked for all kind of pages. I had problem with page for blog posts that was showing ID of the first blog post, not ID of the current page. But this solution solved all that. Of course it is used outside of loop.

$page_object = get_queried_object();
$id     = get_queried_object_id();

Image author: MilanVasek

Share on Facebook0Share on Google+1Tweet about this on Twitter