For many of us, engaging our readers is what we ultimately want to do, and how readers interact with our site is what we want to know. If you are a user of WordPress and you actively use the WordPress.com Stats plugin, you already have all the tools you need to display your most popular posts (by page views) for your readers. Until recently, I have been using the WordPress.com Popular Posts plugin to accomplish this, but I already had everything I needed without using another plugin; and the fewer plugins, the better!
The nice folks over at automattic have opened up there database and have given us an API to retrieve statistical information from WordPress.com’s servers. Now before you get too carried away, the reason I prefer to use this method utilizing WordPress.com’s Stats plugin (which most everyone I know has installed anyway) over other methods is because it causes no extra load on your site, WordPress.com’s server does all the processing for us. This means less database calls for our own sites.
… because all of the processing and collection runs on our servers and not yours, it doesn’t cause any additional load on your hosting account. In fact, it’s one of the fastest stats system, hosted or not hosted, that you can use.
We opened our database for developers to retrieve stats. The API is at http://stats.wordpress.com/csv.php and the plugin includes a handy function, stats_get_csv(), which you can use to get your most popular posts. Here is code you can add to your theme based on the work of Ben Gillbanks:
<?php if ( function_exists('stats_get_csv') && $top_posts = stats_get_csv('postviews', 'days=7&limit=8') ) : ?> <h3>Currently Hot</h3> <ol> <?<span class="hiddenSpellError" pre="">php foreach ( $top_posts as $p ) : ?> <ul> <li><a href="%3C?%3Cspan%20class=">php echo $p['post_permalink']; ?>"><?php echo $p['post_title']; ?></a></li> </ul> <?<span class="hiddenSpellError" pre="">php endforeach; ?> </ol> <?<span class="hiddenSpellError" pre="">php endif; ?>
All you have to do is paste the code above in your theme where you would like your most popular posts to be displayed. You can further customize the date ranges by changing some of the variables within. For instance, if you would like this to display your most popular posts of all time, simply change the ‘days=7’ to ‘days=-1’
Some of the other things you can modify the code with:
period String For use with views table and the 'days' parameter. The desired time period grouping. 'week' or 'month' Use 'days' as the number of results to return (e.g. '&period=week&days=12' to return 12 weeks) limit Integer The maximum number of records to return. Default is 100. "-1" means unlimited.