There are various locations throughout your theme where you might need to get the post ID. For instance you may have a widget in the sidebar that needs the ID or some place in the Header or the Footer that needs the ID. The following is a list of different ways to get the ID.
Inside the loop:
This is a WordPress function for use in the Loop:
the_ID()
or, You can build a function and put in in functions.php
function getthe_loop_postID() { global $post; $thePostID = $post->ID; }
In single.php outside of the loop:
You can build a function and put it in functions.php with
function getthe_single_postID() { global $wp_query; $thePostID = $wp_query->post->ID; }
or you can use post->ID within the single.php template
If you are going to use post->ID within the header or the footer but want it to display on the single post page. You can use:
if is_single() { echo post-ID; }
or what ever it is you want to do with it.
You can use other SQL commands with the post->ID query as well.
For Example:
If you want to see if the post is a particular post use:
post->ID WHERE ID = 17
For the most recent post use:
$post->ID ORDER BY post_date ASC LIMIT 1
For the oldest post use:
$post->ID ORDER BY post_date DESC LIMIT 1