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

I'm trying hard to get the post ID of the current postpage inside a widget class but doesn't work, I know the

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;

 }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742420158a4440522.html

相关推荐

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

    I'm trying hard to get the post ID of the current postpage inside a widget class but doesn't work, I know the

    5小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信