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

How to get post ID of the current pagepost inside a widget?

programmeradmin0浏览0评论

I'm trying hard to get the post ID of the current post/page inside a widget class but doesn't work, I know there's get_the_ID() and some other options but not a single works inside a widget. Here's my code:

public function widget( $args, $instance ) {


   global $wp_query;

   $thePostID = $wp_query->post->ID;
   echo 'Post ID is:' . $thePostID;

}

I'm trying hard to get the post ID of the current post/page inside a widget class but doesn't work, I know there's get_the_ID() and some other options but not a single works inside a widget. Here's my code:

public function widget( $args, $instance ) {


   global $wp_query;

   $thePostID = $wp_query->post->ID;
   echo 'Post ID is:' . $thePostID;

}
Share Improve this question asked Oct 22, 2014 at 7:33 Faizan AliFaizan Ali 2111 gold badge3 silver badges7 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 10

You can make use of get_queried_object() here, which is a wrapper for $wp_query and returns the whole post metadata.

Here's a sample code:

$queried_object = get_queried_object();

if ( $queried_object ) {
    $post_id = $queried_object->ID;
    echo $post_id;
}

Try this:

<?php
global $post;
setup_postdata( $post );
echo "Post's ID: " . get_the_ID();
?>

To just get the ID get_queried_object_id()

Of course, too late but may help others who is looking for the same.

 function widget($args, $instance) {
         global $post;
         echo $post->ID;

 }
发布评论

评论列表(0)

  1. 暂无评论