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;


4 Answers 4


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:

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;

  • Can you explain the code as how it helps the OP
    – bravokeyl
    Commented Dec 31, 2016 at 6:48
  • can yo explain what you want then i can help you. Commented Dec 31, 2016 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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