PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

How-to show popular posts on your WordPress blog?

Note: This article was originally published at Planet PHP on 17 November 2010.
Planet PHP

Yesterday I replaced my list of current PHP articles on this blog with a list of popular articles. I'm sure it's possible in WordPress to get those list if you count the number of comments, but actually I was looking for solution based on real traffic.

Since I'm using WordPress.com Stats, I would like to use the rankings generated by this service or plugin. Searching Google, I found some widget called aoWordPress.com Stats: Top Posts Widgeta which works out of the box (if like to use a widget). In my case I have a custom sidebar with different custom sections using custom code. The following example explains how-to use that code on your website.

First your need to install the WordPress.com Stats plugin

Yes, the WordPress Stats plugin is required, because the list is based on that data. It's possible that you need to wait a couple of days before you can continue with the code below (the system need to store some data first).

The tutorial code

Locate the place where you like to add the list; that can be inside the sidebar, the footer or maybe on your blog's homepage. Add this code snippet:

echo '

Most Popular Articles

    '; $max = 5; $top_posts = stats_get_csv('postviews', "days=7&limit=10"); foreach($top_posts as $post) { $post_obj = get_post($post['post_id']); if (isset($post_obj) && $post_obj-post_type == 'post' && $cnt $max) { echo '
  • .$post['post_permalink'].'"'.$post['post_title'].' ('.$post['views'].')
  • '; $cnt++; }

    Truncated by Planet PHP, read more at the original (another 4041 bytes)