How To Get WordPress Post ID outside the Loop as PHP variable

Posted by

Hi,

In the wordpress loop section, each posts displayed on the page with defined format along with such criteria decided by administrator. The Loop template tag the_ID can be used to easily display the post’s ID inside the post.

Alternatively, inside the the_content filter, declare $id global and use $id to retrieve the post ID. the_ID template tag can be used in this format:

Many time user requires to get Post ID outside the loop template tag. In such cases, the_ID function can not work. In that case, $post->ID will be used to return the post ID. $post is a global object that holds various information about the posts displayed on the page. If the $post is used inside a function, the $post has to be declared as a global variable. For example::

// Works inside of the Loop
function function_name() {
global $post;
$thePostID = $post->ID;
}

or:


// Works in single post outside of the Loop
function function_name() {
global $wp_query;
$thePostID = $wp_query->post->ID;
}

$post->ID can be called directly outside of the Loop too in a single post template, such as ID ?> will print display the post’s ID number. In the multiple posts view page such as index page or archive page, it’s possible to retrieve the get the latest or earliest post ID of all the posts displayed on the page by using an ORDER BY clause to order the posts by date, and then set the number of record to LIMIT 1. Just for example, and there are various way to use the query:

//Get the latest post ID number
$post->ID ORDER BY post_date ASC LIMIT 1

//Get the earliest post ID number
$post->ID ORDER BY post_date DESC LIMIT 1

Thanks,

Shane G.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.