10

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;

}
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;
}
0
1

To just get the ID get_queried_object_id()

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

0

Try this:

<?php
global $post;
setup_postdata( $post );
echo "Post's ID: " . get_the_ID();
?>
0
 function widget($args, $instance) {
         global $post;
         echo $post->ID;

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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