Home > Plugins > How to Display Number of Views Against Each Post in Wordpress

How to Display Number of Views Against Each Post in Wordpress

March 5th, 2009

You must have come across sections on blogs, listing their most popular posts. Have you ever wished that each post on your site showing the number of views against it?

Here’s how you do it:

  • Download the popularity contest plugin
  • Open the associated PHP file (popularity-contest.php)
  • Look for akpc_most_popular function it will look something like below:

function akpc_most_popular($limit = 10, $before = ‘<li>’, $after = ‘</li>’)

{
global $akpc;
$akpc->show_top_ranked($limit, $before, $after);
}

  • Now copy the above function and make a copy let us call it akpc_most_popular_get_post, something like below and change the show_top_ranked also to say show_top_ranked_get_post

function akpc_most_popular_get_post($limit = 0)

{
global $akpc;
$akpc->show_top_ranked_get_post($limit);
}

  • Let us now create the show_top_ranked_get_post, look for this function and copy it to something like shown below:

function show_top_ranked_get_post($limit)

{
if (empty($m) && is_archive()) {
global $m;
}
if (empty($m)) {
global $post;
$m = get_the_time(’Ym’);
}
if (empty($m)) {
return;
}
global $wpdb;
$temp = $wpdb;

$join = apply_filters(’posts_join’, ”);
$where = apply_filters(’posts_where’, ”);
$groupby = apply_filters(’posts_groupby’, ”);
if (!empty($groupby)) {
$groupby = ‘ GROUP BY ‘.$groupby;
}
else {
$groupby = ‘ GROUP BY ‘.$wpdb->posts.’.ID ‘;
}
$posts = $wpdb->get_results(”
SELECT sum(pop.total) as total,$wpdb->posts.ID
FROM $wpdb->posts
LEFT JOIN $wpdb->ak_popularity pop
ON $wpdb->posts.ID = pop.post_id
$join
WHERE
post_status = ‘publish’
AND $wpdb->posts.ID = ” .intval($limit).
“$where
Group By $wpdb->posts.ID
ORDER BY sum(pop.total) DESC”
);
if ($posts) {
foreach ($posts as $post) {
$postviewcount = round($post->total/10); //to correct the count number
print($postviewcount);
}
}
else {
print($before.’(none)’.$after);
}
$wpdb = $temp;
}

}

  • That’s it, now you can call this function anywhere you want by passing the post ID. e.g. <div><?php akpc_most_popular_get_post($post->ID); ?></div>

Hope you find this useful.

Popularity Contest Plugin credit: Alex King

Sid Plugins ,

Viewing 10 Comments

 

Trackbacks

(Trackback URL)

close Reblog this comment
blog comments powered by Disqus