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;
}
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;
}
Share
Improve this question
asked Oct 22, 2014 at 7:33
Faizan AliFaizan Ali
2111 gold badge3 silver badges7 bronze badges
4 Answers
Reset to default 10You 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:
<?php
global $post;
setup_postdata( $post );
echo "Post's ID: " . get_the_ID();
?>
To just get the ID
get_queried_object_id()
Of course, too late but may help others who is looking for the same.
function widget($args, $instance) {
global $post;
echo $post->ID;
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742420158a4440522.html
评论列表(0条)