dzm
dzm

Reputation: 23574

Getting the WordPress Post ID of current post

Anyone know how I can get the post ID of the current page?

So, if I'm on a particular post, inside my header.php, I want to be able to get the current post id.

Thanks!

Upvotes: 61

Views: 231008

Answers (6)

Pikamander2
Pikamander2

Reputation: 8319

In most cases, get_the_ID() will work fine:

$post_id = get_the_ID();

However, in some cases, you may need to use get_queried_object_id() instead:

$post_id = get_queried_object_id();

The reason for this is that the value returned by get_the_ID() is context-dependent and, in some cases, may return a different ID than the main post being queried. For further info, I recommend reading WordPress's documentation regarding The Loop.

Upvotes: 24

borayeris
borayeris

Reputation: 2650

You can use $post->ID to get the current ID.

Upvotes: 24

You can get id through below Code...Its Simple and Fast

 <?php $post_id = get_the_ID();
   echo $post_id;
   ?>

Upvotes: 4

Anoop Saini
Anoop Saini

Reputation: 237

global $post;
echo $post->ID;

Upvotes: 19

Rajnikanth
Rajnikanth

Reputation: 2795

Try:

$post = $wp_query->post;

Then pass the function:

$post->ID

Upvotes: 9

Wade Tandy
Wade Tandy

Reputation: 4144

Try using this:

$id = get_the_ID();

Upvotes: 75

Related Questions