Reputation: 53
Ive been looking all over web i even tried to hire freelancer for help on this but had no luck. While searching i found this how to get popular posts fro selected categories in wordpress? & http://www.queness.com/code-snippet/6546/how-to-display-most-popular-posts-from-a-specific-category-in-wordpress and thats basically what i want but i want the information i get from it split up so i can rank the post.
<?php
$args=array(
'cat' => 3, // this is category ID
'orderby' => 'comment_count',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 6, // how much post you want to display
'caller_get_posts'=> 1
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php }
wp_reset_query(); ?>
With that code it gets the most popular post by comments and what i want to do is basically take the results and add a rank to it like example below.
#1 - post 1
#2 - post 2
#3 - post 3
#4 - post 4
#5 - post5 last post
thanks in advance for any help
Upvotes: 0
Views: 776
Reputation: 135
By your current question I understand the following:
So your result could be:
1 Post A (comment count 500)
2 Post B (Comment count 499)
3 Post Z (Comment count 200)
This is how I would do it:
<?php
function get_popular_posts()
{
$sql="SELECT comment_count, guid AS link_to_post, post_title
FROM wp_posts
WHERE post_status = "publish" AND post_type = "post"
ORDER BY comment_count DESC
LIMIT 5"
return $wpdb->get_results($sql, OBJECT)
}
$post_objects = get_popular_posts();
$i = 1;
foreach($post_objects as $object)
{
echo 'Post: ' . $i . '#' . ' ' . $post_title . ' ' . $link_to_post . ' ' . $comment_count;
$i++;
}
?>
Haven't tested the code. But it should take five "top posts" from the database. Left in the comment_count for explanatory reasons.
Upvotes: 0
Reputation: 418
May be this idea will help you.
Use get_comments_number( $post_id ) function
To get number of comment and then do a if else loop for displaying rank.
$num_comments = get_comments_number(); // get_comments_number returns only a numeric value
if ( comments_open() ) {
if ( $num_comments == 0 ) {
$rating= 0 ;
} elseif ( $num_comments > 1 ) {
$rating= 1 ;
} else {
$rating= 0 ;
}
}
Thanks
Upvotes: 1