frankd
8/25/2015 - 10:29 PM

How to Track post views without a plugin using post meta (Wordpress) POPULAR POSTS PAGE SNIPPETS

How to Track post views without a plugin using post meta (Wordpress) POPULAR POSTS PAGE SNIPPETS

Use the following snippet to track post views on your wordpress blog. 
The first thing you want to do is add this snippet to the functions.php of your wordpress theme. 
Follow step 1. and step 2. to track and display the number of views for each post.

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);
    }
}
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
$args = array(
    'posts_per_page' => 10,
    'meta_key' => 'post_views_count',
    'orderby' => 'meta_value_num',
    'order' => 'DESC'
);
$top_posts = new WP_Query($args);
while ($top_posts->have_posts()) : $top_posts->the_post();
    // Your post loop content
endwhile;
wp_reset_postdata();