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.
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI'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.
You can call "id" but object call as "ID" Please Replace with this code
global $post ;
$id = $post->ID ;
id
is lowercase. Try this and it should work for you @bob.
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();
});