Here is the solution to easily find the WordPress post views count.
According to the reports from BuiltWith, WordPress is the most popular CMS used for websites. We can create, store and manage news documents, images, video and any other online content type imaginable in WordPress. But unfortunately there is no inbuilt feature for finding the WordPress post views count. In the following example we are explaining how to find the WordPress post views count without using any third party plugin. Very minimal codes have been used in this example.
WordPress Post Views Count
We have to make some changes in the WordPress theme files. I.e. Here we have to add a few lines of codes in functions.php, single.php and page.php files. Also we have to add a few lines of code where we have to fetch the post views count.
Add the below code snippet to functions.php.
//SET POST VIEW 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); } } //GET POST VIEW COUNT 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'; }
Now, ADD THE below CODE snippet AT THE BEGINNING OF SINGLE.PHP & PAGE.PHP.
$id = get_the_ID(); setPostViews($id);
finally, use THE below CODE snippet TO DISPLAY THE POST VIEWs COUNT.
<?php $posts = new WP_Query( array( 'posts_per_page' => -1, 'post_status' => 'publish') ); while ( $posts->have_posts() ) : $posts->the_post(); $meta_values = get_post_meta( get_the_ID() ); $post_view_count = $meta_values['post_views_count'][0]; ?> <div class="title"> <?php the_title(); ?> </div> <div class="post-view-count"> <?php echo $post_view_count; ?> </div> <?php endwhile; wp_reset_postdata(); ?>
Note: Use this code as a reference and make needful customization for any particular requirement. If we are using a purchased template then we have to make these changes each and every time after updating the template. Otherwise we have to use child themes. It is compatible with version 4.3.1 of WordPress.
WordPress post views count is normally used in online magazines, audio or video sharing platforms. It is used to display the user engagement. Here are some of the websites using this feature.