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;


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();
 function widget($args, $instance) {
         global $post;
         echo $post->ID;

  • 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. – Nanhe Kumar 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.