I'm building a function within functions.php
Within my function I want to make use of the post id of current post. How do I do this?
The last thing I tried was this:
global $post ;
$id = $post->id ;
However, this returns an empty string.
I'm building a function within functions.php
Within my function I want to make use of the post id of current post. How do I do this?
The last thing I tried was this:
global $post ;
$id = $post->id ;
However, this returns an empty string.
Share Improve this question asked Mar 14, 2017 at 6:25 bobbob 2491 gold badge6 silver badges16 bronze badges2 Answers
Reset to default 2You can call "id" but object call as "ID" Please Replace with this code
global $post ;
$id = $post->ID ;
It all depends on where you have placed your hook. If you hook after 'wp' then you should be able to access the global $post object just fine.
Before that, the object has not been initialized and thus its not accessible.
You could hook into the template_redirect as follows.
add_action('template_redirect', function() {
$post_id = get_queried_object_id();
});