If you don’t want to burden your server with too many plugins, perhaps using a certain php code to display several features that usually easy to active with plugins will help your server, such as displaying related post without plugin and you can display most popular post without plugin too. This php code serves similar intention as popularity plugin, but the different is it’s php code of which we must do a little work with our function.php and other folders depend on where you want to put it.

The first thing you need to do now is back up your function.php file in case something wrong happen, and open your function.php file add this code within it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function most_popular_posts($no_posts = 10, $before = '<li>', $after = '</li>', $show_pass_post = false, $duration='') {
global $wpdb;
$request = "SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS 'comment_count' FROM $wpdb->posts, $wpdb->comments";
$request .= " WHERE comment_approved = '1' AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status = 'publish'";
if(!$show_pass_post) $request .= " AND post_password =''";
if($duration !="") { $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date ";
}
$request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts";
$posts = $wpdb->get_results($request);
$output = '';
if ($posts) {
foreach ($posts as $post) {
$post_title = stripslashes($post->post_title);
$comment_count = $post->comment_count;
$permalink = get_permalink($post->ID);
$output .= $before . '<a href="' . $permalink . '" title="' . $post_title.'">' . $post_title . '</a> (' . $comment_count.')' . $after;
}
} else {
$output .= $before . "None found" . $after;
}
echo $output;
}

What we have just done is create a new function called most_popular_posts. Now all we have to do is use our new function. Open sidebar.php and add wherever you want the list to appear. Using the default Kubrick theme as an example, you would have this …

We have created a new order inside our function.php file called most_popular_posts. The next step is telling our theme to display the newly order, open your sidebar or footer or anywhere you want to add the following code:

1
2
3
 <li><h2>Popular</h2>
<ul><?php most_popular_posts(); ?></ul>
</li>

If you want to control number of articles inside your popular post, you can change in the line $no_posts = 10. Thanks to RiteTurnOnly for making this tutorial available online!

Related posts:

  1. Display Related Post In Wordpress Without Plugin
  2. How To Shorten Wordpress Blog Post URL For Twitter
  3. Tutorial To Show Ads only on Wordpress Homepage
  4. Tutorial To Split Wordpress Post Into Separated Pages
  5. Wordpress 2.9 Will Be Released On October 30