Posted on May 04, 2010 by Jimmy K. in
Tutorials
I wanted to be able to track the number of views each one of my posts gets in a very general way so I could create a “popular articles” section on my blog. I looked through the MySQL database and couldn’t find any traces of WordPress tracking post views by default. So! What I did was write a nifty little set of functions that I’m pretty sure don’t follow any development standards.
Update: I’m slowly tackling the obstacle of converting this tutorial into a WordPress plugin.
First, I created a table in the MySQL database to keep track of the post views and I update the table every time a post is loaded in the browser. I only count specific post views (where ./?p=XYZ) is in the URL.
Here is the MySQL statement to create the table:
CREATE TABLE IF NOT EXISTS `wp_postviews_z` (`PostID` mediumint(8) unsigned NOT NULL, `NumViews` mediumint(8) unsigned NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Then I wrote a function called
jTrackPostView(), which basically updates the database whenever a post is being viewed. I placed this code into the
index.php file. All it really does is says: if
$_GET['p'] is set, call the
jTrackPostView() function because we only want to track the post view if we’re actually reading the entire post (not the excerpt).
<?php print('This is PHP.'); ?>
To display the popular posts, I placed this code into the
sidebar.php file:
<table style="width: 250px;">
<?php
$aViewCounts = array();
$oViewsQuery = mysql_query("SELECT `PostID`, `NumViews` FROM `wp_postviews_z` ORDER BY `NumViews` DESC LIMIT 10;") or die(mysql_error());
$sPopularQuery = "SELECT `ID`, `post_title` FROM `wp_posts` WHERE `ID` = '0'";
while ($oViewsResults = mysql_fetch_assoc($oViewsQuery)) {
$aViewCounts[$oViewsResults['PostID']] = $oViewsResults['NumViews'];
$sPopularQuery .= " OR `ID` = '" . $oViewsResults['PostID'] . "'";
}
$sPopularQuery .= " ORDER BY `post_title` ASC;";
$oQuery = mysql_query($sPopularQuery) or die(mysql_error());
$y = 0; while ($oResults = mysql_fetch_assoc($oQuery)) {
print('<tr style="width: 250px;">');
print('<td style="width: 250px;"><ul><li>');
print('<a href="./?p=' . $oResults['ID'] . '">' . $oResults['post_title'] . '</a> <span>(' . $aViewCounts[$oResults['ID']] . ')</span>');
print('</li></ul></td></tr>');
}
?>
</table>
I really want to help other people by converting this into a lightweight WordPress plugin, but I don’t know how to do that yet. Hopefully by the end of May I’ll be better equipped to tackle that.
Can someone please suggest where I can find a decent tutorial for writing WordPress plugins? If so, please let me know in the comments.
Tags: Awesome,
PHP,
Tutorials,
WordPress