How to display WordPress post view count without a plugin

Tutorial 1

Use this code in functions.php

function rm_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', 'rm_post_view_count');

Or use this code in your 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);
		}
	}

then 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 2

Add this code your functions.php

// 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);
    }
}

Add 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()); ?>