WordPress logo

Retrieve and get WordPress post ID outside the loop

In WordPress all posts and pages have a unique anchor identifier in the form of numeric post ID. Retrieving the ID inside the Loop, where WordPress processes and displays each of the posts to be displayed on the current page, is done through the PHP function the_ID() or get_the_ID().

The_ID template tag can be used in the following format:

<?php the_ID(); ?>
or
<?php get_the_ID(); ?>

Outside the Loop or out of the context of the post, such as in the header or the footer and even sidebar area in WordPress templates, the_ID() cannot be used as a function. Instead, $post->ID is used to return the post ID. $post is a global object that holds various information about the posts displayed on the page. So $post->ID will return the post ID of the post. It the $post is used inside a function, the $post has to be declared as a global variable. For example:

// Inside the Loop
function function_name() {
global $post;
$thePostID = $post->ID;
}
or
// Outside the Loop
function function_name() {
global $wp_query;
$thePostID = $wp_query->post->ID;
}

In the multiple posts view page such as index page or archive page, it’s possible to retrieve the latest or earliest post ID of all the posts displayed by using an ORDER BY clause to order the posts by date, and then set the number of record to LIMIT 1.

//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

Written By

Panagiotis (pronounced Panayotis) is a passionate G(r)eek with experience in digital analytics projects and website implementation. Fan of clear and effective processes, automation of tasks and problem-solving technical hacks. Hands-on experience with projects ranging from small to enterprise-level companies, starting from the communication with the customers and ending with the transformation of business requirements to the final deliverable.