0

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.

0

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 Mar 19 '17 at 15:01
0

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 Mar 15 '17 at 22:51
  • @bob I updated my answer with an example that should work from the functions.php file – Patrizio Mwange Mar 19 '17 at 12:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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