Single Post

How To Track & Display WordPress Post Views Functions Without Any Plugin
- WordPress
- no responses
- Sep 02, 2019
First Step:
Use this code in functions.php
function pr_post_view_count(){ if ( is_single() ){ global $post; $count_post = esc_attr( get_post_meta( $post->ID, '_post_views_count', true) ); if( $count_post == ''){ $count_post = 1; add_post_meta( $post->ID, '_post_views_count', $count_post); }else{ $count_post = (int)$count_post + 1; update_post_meta( $post->ID, '_post_views_count', $count_post); } } } add_action('wp_head', 'pr_post_view_count');
Or use this code single.php
if ( is_single() ){ global $post; $count_post = esc_attr( get_post_meta( $post->ID, '_post_views_count', true) ); if( $count_post == ''){ $count_post = 1; add_post_meta( $post->ID, '_post_views_count', $count_post); }else{ $count_post = (int)$count_post + 1; update_post_meta( $post->ID, '_post_views_count', $count_post); } }
Use this code for display post counter
global $post; $visitor_count = get_post_meta( $post->ID, '_post_views_count', true); if( $visitor_count == '' ){ $visitor_count = 0; } if( $visitor_count >= 1000 ){ $visitor_count = round( ($visitor_count/1000), 2 ); $visitor_count = $visitor_count.'k'; } echo esc_attr($visitor_count);
Tutorial TWO:-
Add this codes from the following block in your themes function.php file. It will configure your theme to enhance this functionality.
// function to display number of posts. 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 to 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); } }
dd this code to your single.php file
<?php setPostViews(get_the_ID()); ?>
Add this code for display post counter
<?php echo getPostViews(get_the_ID()); ?>
The following image manifests that the code works finely on my local server: