How can $post_id be used while echoing posts in single.php?

Is it a global variable?

  • 2
    when you ask a question you should supply as much relevant context as possible. Please edit your question, to include all relevant information, don't ask people to guess what is it that you mean. Commented Mar 28, 2018 at 3:40

3 Answers 3


No, $post_id is not a global variable. You can see a list of global variables WordPress creates here: https://codex.wordpress.org/Global_Variables

$post_id is just a common naming convention for a variable that contains a post ID. In tutorials and example code it shows that the value is expected to be a post ID, but you still need to have set its value somewhere else in the code.

If you are inside The Loop you can get the ID of the current page or post in the loop with $post_id = get_the_ID(). If you are outside The Loop and want to get the ID of the currently queried post or page you can use $post_id = get_queried_object_id().

Another way you might get a post ID is in a hook callback. For example, in the post_thumbnail_size hook the callback receives a post ID as the 2nd argument:

function wpse_299132_post_thumbnail_size( $size, $post_id ) {
    return $size;
add_filter( 'post_thumbnail_size', 'wpse_299132_post_thumbnail_size', 10, 2 );

But that's just the name used in the documentation to make it clear what the variable contains. You can call it anything you like. This is also valid, for example:

function wpse_299132_post_thumbnail_size( $size, $myPostId ) {
    return $size;
add_filter( 'post_thumbnail_size', 'wpse_299132_post_thumbnail_size', 10, 2 );

$myPostId is the 2nd argument, so will contain a post ID. But what you call it doesn't matter.


$post_id is not a global variable. $post is a global variable. You can use

global $post;
$post_id = $post->ID;

In some cases, such as when you're outside The Loop, you may need to use
get_queried_object_id() instead of get_the_ID().

$postID = get_queried_object_id();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.