So I’ve installed a new plug-in called View Count by Michael O’Connell. Was pretty simple. Getting the view count was the 1st step in what I was trying to accomplish. I wanted to add a list of the top viewed posts in my sidebar. Installing the plug-in was pretty simple as I just dropped the folder and file into my WordPress wp-content\plugins directory.
Once activated, there was a new column in my wp_posts table called view_count. The default value is 0, but this’ll change once this plug-in is ran for some time.
So the next step was to create the MySQL query to get the x most viewed posts. Turns out executing the query was easier than I thought:
$results = $wpdb->get_results("SELECT ID, post_title, view_count FROM $wpdb->posts ORDER BY view_count DESC LIMIT $limit" );
Then for each result in the array of results you got back, I did the following which links to the post with title and displays how many views it has:
echo '<li><a href="' . get_permalink( $result->ID ) . '">' . $result->post_title . '</a> [<strong>' . $result->view_count . '</strong>]</li>';
And that’s basically it!
I did notice 1 problem with with the plug-in’s instruction. It states to show your posts sorted by view count, to just add this link: ?ordrby=view_count, however, the correct link according to the code does have the ‘e’ which is ?orderby=view_count.
Apparently, it’s also counting when I’m writing/editing the post. I frequently save due to times in the past when I lost complete essays by accidentally closing the tab or if my browser crashes and each reload counts as 1 view. I’ve changed it so it ignores my views, so it seems like a good workaround for now.