57

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!

1

6 Answers 6

73

Try using this:

$id = get_the_ID();
1
  • Awesome, better that get_the_ID() which return error if shown in 404. Thank you :)
    – Jodyshop
    Commented Aug 5, 2021 at 9:39
24

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

2
  • 4
    Don't forget you'll have to globalize $post first, if you're using this method within a class. Also, this will only work once the $post is actually available, which would generally be after the 'init' action.
    – Tom Auger
    Commented Aug 8, 2013 at 13:59
  • Throws warning after 3.0
    – norahCii
    Commented Jan 18 at 20:51
22

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.

2
  • 2
    this works, and I don't know why Commented Sep 7, 2022 at 11:08
  • 1
    @jaafarNasrallah - The reason it works is because the "ID" in "get_the_ID" is intentionally meant to be context-dependent, so its value can change depending on what part of "The Loop" you're in. By contrast, the ID in "get_queried_object_id" specifically refers to the ID being queried, which is what you're probably looking for if you're viewing this question. Commented Feb 16, 2023 at 7:21
19
global $post;
echo $post->ID;
3
  • 6
    This answer would be better if it did more than just post a code solution. It's helpful to provide a short explanation of the code. (Also, I'm not a PHP expert, but it seems to me that after assigning a value to $the_post_ID, it would be appropriate to use that same variable name in the echo statement, instead of $thePostID). Commented May 4, 2015 at 6:26
  • 1
    Well it seems he's removed the error with the echo, but 'you Be Damned' if you think he's going to explain his code @PeterDuniho Commented Feb 27, 2016 at 22:56
  • Check this stackoverflow.com/questions/22351038/…
    – user7118434
    Commented Dec 12, 2016 at 13:23
9

Try:

$post = $wp_query->post;

Then pass the function:

$post->ID
4

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

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

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