Retrieve and Get WordPress Post ID Outside the Loop as PHP Variable

»»»Retrieve and Get WordPress Post ID Outside the Loop as PHP Variable
In WordPress, each post has unique anchor identifier in the form of numeric post ID. When inside the Loop, where WordPress processes and displays each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags, 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 the following format:

<?php the_ID(); ?>

Outside the Loop or out of the context of the post, such as in header of footer and even sidebar area in the templates of WordPress’s blog, the_ID() cannot be used as a function. Instead, $post->ID will be used to return the post ID (the syntax can also be used inside the Loop of the post by declaring $post as global). $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:


// Works inside and outside 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 <?php echo $post->ID ?> will print display the post’s ID number.

In the multiple posts view page such as index page or archive page, you should use custom WP_Query or query_posts to return the content that you want as there may be more than one post IDs that are returned.

By |2016-12-09T08:42:14+00:00December 9th, 2016|Categories: Web Publishing|Tags: |51 Comments

About the Author:

LK is a technology writer for Tech Journey with background of system and network administrator. He has be documenting his experiences in digital and technology world for over 15 years.Connect with LK through Tech Journey on Facebook, Twitter or Google+.