I am trying to display the most popular posts based on comments in my sidebar. I want the post thumbnail to show up nex开发者_StackOverflow中文版t to the title but when I sort my posts using 'orderby=comment_count' the thumbnail disappears. If I show the posts based on the category name the thumbnail shows up. For reference, here is my code:
<?php $post_by_comment = new WP_Query('orderby=comment_count&posts_per_page=6'); ?>
<?php while ($post_by_comment->have_posts() ) : $post_by_comment->the_post(); ?>
<?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail();
}
?>
<?php endwhile;?>
If I use the exact same code but change:
<?php $post_by_comment = new WP_Query('orderby=comment_count&posts_per_page=6'); ?>
to
<?php $post_by_comment = new WP_Query('category_name=categoryname&posts_per_page=6'); ?>
the post thumbnails show up just fine. What am I doing wrong here?
Try get_the_post_thumbnail and pass it the ID you are looking for.
get_the_post_thumbnail($post_by_comment->ID, 'thumbnail');
I think why this is going wrong is perhaps that the_post_thumbnail expects the ID to be $post->ID rather than $post_by_comment->ID (as you have).
I'd also use get_posts rather than starting a new query if this is just a side listing, rather than the main content of the page.
精彩评论