The question:
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;
}
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
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;
}
Method 2
To just get the ID
get_queried_object_id()
Of course, too late but may help others who is looking for the same.
Method 3
Try this:
<?php
global $post;
setup_postdata( $post );
echo "Post's ID: " . get_the_ID();
?>
Method 4
function widget($args, $instance) {
global $post;
echo $post->ID;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0