Simple get post views counter without plugin in WordPress

Easy get post views counter and easy installation by copy code bellow to functions.php of your WordPress themes. This functions counts and displays all hits/views in each post on your blog and saves it to the database. Views are counted each time a page or post is requested/refreshed (unique and non-unique visitors) and displayed in the posts entry meta. This functions works on all posts and pages – no administrations necessary

Step 1: Get post views counter code

Copy code bellow to functions.php of WordPress themes

function hr_set_post_views($postID) {
		$count_key = 'hr_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);
		}
	}
	//To keep the count accurate, lets get rid of prefetching
	remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
	function hr_track_post_views ($post_id) {
		if ( !is_single() ) return;
		if ( empty ( $post_id) ) {
			global $post;
			$post_id = $post->ID;
		}
		hr_set_post_views($post_id);
	}
	add_action( 'wp_head', 'hr_track_post_views');

	function hr_get_post_views($postID){
		$count_key = 'hr_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";
		}
		return $count.'';
	}

Step 2: Show Post views counter

Open single.php file in your WordPress themes, insert this code to positions where you want to show

<?php echo hr_get_post_views(get_the_ID()); ?>

Thanks for reading this tip.

Share this :

Comments are closed.

Related post

Free Responsive Website templates

ThemeVina is Best site for free sharing and download Wordpress themes, Joomla templates, Responsive website templates and more HTML templates.

All template in Site are free. You can download and install for your site.

Contact us

  • Brand: Theme Vina
  • Email: admin@themevina.com
  • Website: www.themevina.com
  • Address: 367 Tran Hung Dao Street
  • Location: Thai Binh City, Thai Binh, Viet Nam

Newsletter