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