How to get post id inside and outside the loop in single post WordPress


06.05.2009

How to get post id inside and outside the loop in single post WordPress WordPress uses an identifier for each post that can be returned as the post ID. While inside the post’s loop, there is a specific template tag to get the post ID, but don’t work anymore when outside the loop.

If you don’t know where the loop starts and ends, look for the following codes:

Loop start:
if ( have_posts() ) : while ( have_posts() ) : the_post();

Loop end:
endwhile; endif;

To get the post id inside the loop, you can simply use the following function:
the_ID();

Like I said before, the the_ID() function doesn’t work outside the loop, so you will have to declare $post global and use $post->ID to return the post’s id.
global $post;
$post->ID;

Please note this works and has been tested for WordPress 2.7.1 and other recent versions. If you are using an older or a beta version it might not work for you. If you’re having problems, let me know.
As always, feedback is appreciated.

Tags: post, loop, work, wordpress, outside, inside, know, following, global, don’t, the_id, function, have_posts, post’s, tested, works, recent, versions, note, please, declare, single, return, using, older, always, feedback, appreciated, problems, having