最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I get the post id from within functions.php

programmeradmin0浏览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.

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 badges
Add a comment  | 

2 Answers 2

Reset to default 2

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

});
发布评论

评论列表(0)

  1. 暂无评论