Wordpress - What is $post_id? is it a global variable in WordPress?

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;