This is probably the shortest way of showing the popular posts in your plugin and it is the same way I use on the sidebar of this blog.

First of all open your functions.php file inside your theme folder.
If it doesn’t exist, just create an empty file named functions.php in your current theme folder.

function get_mostpopular(){
 global $wpdb;
 $popular_posts = $wpdb->get_results("SELECT id,post_title FROM {$wpdb->prefix}posts ORDER BY comment_count DESC LIMIT 0,5");
 foreach($popular_posts as $post) {
 if ($a%2){$turn='class="odd"';}else{$turn='';}
 print "<li $turn><a href='". get_permalink($post->id) ."'>".$post->post_title."</a></li>\n";
 $a++;
 }
}

Copy this code between tags. Currently this code shows 5 posts with the highest number of comments. If you want to show more just change the 3rd line where it says comment_count DESC LIMIT 0,5 and replace 5 with the number you want.

Also I add a class “odd” to every other line to generate the different color on each line. Now save your functions.php and open up your sidebar.php.

And wherever you want to show the popular posts just call the function from there.

<ul><?php get_mostpopular(); }?></ul>




Extra:

The current styles I use for this list is as follows;

#sidebar li{
	padding: 5px 15px;
	background-color:#f2f0f7;
	border-bottom:1px solid #fff;
}
#sidebar li.odd{background-color:#ebe8f1;}

You might want to change the “#sidebar” to the id or class of your own sidebar.





Related Posts

Be the first to comment

Leave a Reply