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

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

Leave a Comment