WordPress: Display Most Popular (Viewed) Posts without a plugin

OK this one was tricky, but resolved. With this method you can display most popular posts by views (not by comments, in my casi I hadn’t comment on each post). It uses a custom-value that records each hit on each post and then it is possible to query them by meta-value:

Add this on functions.php:

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

The add this when the loop starts within single.php:

setPostViews(get_the_ID());

Finally, query the posts by this meta-value, por example in the sidebar.php:

<?php
	query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC');
	if (have_posts()) : while (have_posts()) : the_post(); ?>
	<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
	<?php
	endwhile; endif;
	wp_reset_query();
?>

Leave a Reply