We now have post views in WordPress

I looked around and found https://www.themexpert.com/blog/track-display-post-views-in-wordpress
Which had code for me to use. Then I found another site that mentioned about add_action so I added the below code to the end of my theme’s 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);
    }
}
// Remove issues with prefetching adding extra views
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function postview_after_date($date, $d, $post_id)
{
	return $date . " | " . getPostViews(get_the_ID());
}
add_action('get_the_date', 'postview_after_date', 10, 3);

So whenever the blog tries to print out the date for the post it would also print out ” | ” and followed by number of views.

Then in single.php (in the theme) I added this line of code:

setPostViews(get_the_ID());

after the the following code:

if ( comments_open() || get_comments_number() ) {
                     comments_template();
}

And that looks like it for post view counts.

I tested it made sure that while viewing a single post, the view count would increase and the views also show on the index page.

Another mission accomplished.

           

Leave a Reply

avatar
  Subscribe  
Notify of