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

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;



Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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;

Method 2

To just get the ID get_queried_object_id()

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

Method 3

Try this:

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

Method 4

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


All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments