Create most popular post on WordPress themes

There is a lot of way how to increasing user time visit or time on site for website or blog. Provide good navigation and links is the best way to keep user stay tune on our blog. A lot of user, like me exciting to click related post link and most popular post link when visiting blog. Source code bellow, is sourcode how to get most populer post on wordpress themes. You can placing this source code in your sidebar or wherever you want.

<?php
/* Handle the most Popular Posts Here */
/*Query most popular post fromdatabases*/
$sql = "SELECT post_date, post_title, post_name, comment_count from wp_posts ORDER BY comment_count DESC LIMIT 10";
$searches = $wpdb->get_results($sql);
?>
<ul>
<h3><?php _e('Popular Post'); ?></h3>
<?php
foreach ( $searches as $searchz ){
$dtp = explode(" ", $searchz->post_date);
$tdstr = preg_replace("/\-/", "/", $dtp[0]);
echo '<li>' . '
<a href="http://www.yourdomain.com/' . $tdstr . '/' . $searchz->post_name . '" title="' . $searchz->post_title .
'">' . $searchz->post_title . '</li>';
}
?>
</ul>
<?php

On the sourcode above, first we select post_date, post_title, post_name, comment_count from table wp_posts and then ordered the result by comment count descending. You also can change count of result for displayed by change the limit.

Incoming search terms for the article:

2 Comments

  1. .

    05.05.2009

    Thanks a lot. I’ve been looking for such a code ages ago.

    If I may ask, I tried it, but it displayed the posts in order of timing. I mean, it seems that it selected the most popular, and then ordered them according to time of posting. Is there a way I can change that?

    Also, is there a way I can add between brackets the number of views of each post?

    Thanks a lot.
    .

    • mupet

      05.06.2009

      @., thanks for commenting, on the code above, we select the popular post that identified by number of comments (most commented). I cant ordered the result by number of views of the posts, because there is no somethink like ‘post_view_count’ on post table. To showing number of post, you have to do litle hack by creating new table for saving number of views of the posts, or you can consider this plugin , after implementing this plugin, change your query becomes somethink like this
      SELECT wp_posts.post_date, wp_posts.post_title, wp_posts.post_name, wp_posts.comment_count, mostaccessed.cntaccess from wp_posts,mostaccessed where mostaccessed.postnumber=wp_posts.id ORDER BY wp_posts.comment_count, mostaccessed.cntaccess DESC LIMIT 10