WordPress: How to get the post id outside single post ( header, footer, sidebar )


11.05.2009

I told you how to get the post id in single post inside and outside the loop, but maybe you need to get it in footer, header, sidebar or other theme file and you will need to use the wp_query function.

The the_ID() and $post->ID functions only work in the single post template, so if you want to get the post id in another theme template, you will need to use the following function:
// Get the id outside single post
global $wp_query;
$post_id = $wp_query->post->ID;

The $wp_query can be used in many ways, allowing you to query all the wordpress database with all the possible commands, so stay put for future articles on how to use the wp_query to do some random things on your WordPress blog!
As always, feedback is appreciated!

Tags: post, wp_query, single, outside, wordpress, function, theme, template, footer, header, sidebar, stay, commands, allowing, future, query, database, possible, things, always, feedback, appreciated, blog, ways, some, random, articles, want, file, the_id