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!
Check the answer for this question stackoverflow.com/questions/22351038/β¦
β user7118434Dec 12, 2016 at 13:31
Try using this:
$id = get_the_ID();
Awesome, better that get_the_ID()
which return error if shown in 404. Thank you π
β JodyshopAug 5, 2021 at 9:39
You can useΒ $post->ID
Β to get the current ID.
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 AugerAug 8, 2013 at 13:59
global $post;
echo $post->ID;
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
).
β Peter DunihoMay 4, 2015 at 6:26
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
β Phill HealeyFeb 27, 2016 at 22:56
Check this stackoverflow.com/questions/22351038/β¦
β user7118434Dec 12, 2016 at 13:23
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()
.
$post_id = get_queried_object_id();
this works, and I don’t know why
β jaafar NasrallahSep 7 at 11:08
Try:
$post = $wp_query->post;
Then pass the function:
$post->ID
You can get id through below Code…Its Simple and Fast
<?php $post_id = get_the_ID();
echo $post_id;
?>
source : https://stackoverflow.com/questions/4893435/getting-the-wordpress-post-id-of-current-post