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.

2 Answers 2


You can call "id" but object call as "ID" Please Replace with this code

global $post ;
$id = $post->ID ;
  • Yes, this is likely because the in the question the id is lowercase. Try this and it should work for you @bob.
    – user111400
    Commented Mar 19, 2017 at 15:01

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();

  • which hooks might be appropriate?
    – bob
    Commented Mar 15, 2017 at 22:51
  • @bob I updated my answer with an example that should work from the functions.php file Commented Mar 19, 2017 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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