Creating a WordPress post views counter without a plugin may sound a little tough. However, you can actually achieve a custom post views counter in a few minutes. Allow other visitors see how popular your blog really is.

Post Views Counter

Adding Custom Post Views Counter To WordPress Theme

Let’s start things off by locating our functions.php inside our WordPress theme. You can include our WordPress posts views counter script in elsewhere if your familiar with WordPress. For now, we will be adding the view counter script directly to our functions file.

Save Post Views Count To WordPress Database

/*
*
* Post View's Counter
*
*/
add_action('wp_head','ensure_views_counter');
function ensure_views_counter(){
	// Only Count On Posts
	if(!is_singular('post')){
		return false;
	}

	// Get Post ID
	$currentID = get_the_ID();

	// Check For Current Views
	$totalViews = get_post_meta($currentID, '_post_views_count', true);

	// Check If Is Int
	if(!is_numeric($totalViews)){
	  $totalViews = 0;
	}

	// Increase by 1
	$totalViews++;

	// Update the total views
	update_post_meta($currentID,'_post_views_count', $totalViews);
}

This WordPress post views snippet is the essential piece. It’s actually pretty simple when you break it down. Let’s look over the actions taking place.

First, we are firing the post views counter using “wp_head”. We use this action simply because it runs on every page within the front end of WordPress.

Now, we may want to limit to only a particular post type rather letting it run on pages and other custom post types. For this we are simply checking if it’s a singular post within the default post type in this example. You can change that to your needed post type or use an array to include multiple.

Next we check the post meta, which is how we are storing the view counter number in the database. This allows for a site with unlimited post to easily store unique page view counts for each page without bloating the WordPress DB.

To do so, we now need the correct post ID. WordPress makes that part easy using get_the_ID() function.

Easy Post Views Counter Math

For this part of setting up the post view counter math, we need to check the post meta key for any previous number stored. The key interest here is making sure we know if a post has had views before. Posts without page views will not return a 0 as they actually do not exists yet. The key will be created for each post as it gets its first page view.

To check if the post has views yet, we are simple checking if WordPress returns a numeric value. If not, we set the value to 0. Now we have a post view count number regardless.

Quickly do the complicated post views count math by taking the variable and adding ++ does the trick in PHP. This just increases the post view counter by 1.

Saving Post Views Count

Updating the saved post view count in the post meta requires one line. Using update_post_meta() WordPress function will now save the final number that was calculated above. It’s important to note that using the post ID and same key is required. The 3rd parameter is the updated post view count.

That’s it for the actual function to collect post views in WordPress. Now of course, what good is collecting page views on blog post with out being able to see them or show them to other visitors.

Display WordPress Post Views On The Front-end.

There are many ways you can go about displaying the post views count on the front end of your WordPress website. We will start by creating the primary function that retrieves the post view count that we saved in the 1st function.

The primary post views display function is really small. It’s doesn’t require but a single line.

/*
*
* Get The Post View's total
*
*/
function ensure_get_the_views(){
	// Only Count On Posts
	if(!is_singular('post')){
		return false;
	}

	// Get Post ID
	$currentID = get_the_ID();

	// Check For Current Views
	$totalViews = get_post_meta($currentID, '_post_views_count', true);

	// Check If Is Int
	if(!is_numeric($totalViews)){
		$totalViews = 0;
	}
	
	// Return the number.
	return $totalViews;
}

This function will only return the post views count as a single integer. You could use this function in your template files and it would work fine. But sometimes you want to display a post view phrase that makes sense. An example would be showing it as: 32 views or 1 view.

Making sure we cover the singular and plural page view phrases adds a sense complexity. Let’s take a look at how not so complex such view counter phrase code can be. Below we will modify the function above to include dynamic phrases.

/*
*
* Get The Post View's total
*
*/
function ensure_get_the_views($single = 'View',$plural = 'Views'){
	// Only Count On Posts
	if(!is_singular('post')){
	   return false;
	}

	// Get Post ID
	$currentID = get_the_ID();

	// Check For Current Views
	$totalViews = get_post_meta($currentID, '_post_views_count', true);

	// Check If Is Int
	if(!is_numeric($totalViews)){
	   $totalViews = 0;
	}

	// Use Phrases For Views
	if($totalViews = 0){
	   $totalViews = $totalViews." $single";
	} elseif($totalViews = 1){
	   $totalViews = $totalViews." $single";
	} elseif($totalViews > 1){
	  $totalViews = $totalViews." $plural";
	}
	
	return $totalViews;
}

Now, we can use a function that includes views phrases. You can add this function like this:

// The default:
echo ensure_get_post_views();
// Returns: 32 Views
echo ensure_get_post_views('Person Read', 'People Read');
// Returns: 32 People Read

Inject Post Views Count Into Post

The function above will allow you to place the views counter pretty much anywhere in your template you need. That great’s and all but what if you just want to quickly inject the post views counter into your blog post via a filter?

Every WordPress theme has its own actions and filters but most of them all use the WordPress core function of the_content() to display the page and post contents. We can tie into into that function to display our post views count in the top or bottom of our posts.

/*
*
* Display Post View's total before post content
*
*/
add_filter('the_content','ensure_insert_post_views');
function ensure_insert_post_views($content){
	if(is_singular('post')){
		return ensure_get_post_views().$content;
	} else {
		return $content;
	}
}

How To Query Posts Based On Post Views Count

So we finally have a WordPress post views counter integrated into our site. It’s shows the views on each post in WordPress. Now we can go a step further and create a popular post widget.

Technically we are going to create a simple WordPress shortcode to get popular posts. We can use that popular posts shortcode to place the popular posts wherever you like.

/*
*
*	Popular Posts By View Count / Shortcode - ex. [ensure_popular_posts limit="5"]
*
*/
function ensure_popular_posts_build($atts, $content = null){
    extract(shortcode_atts(array(
	  "limit" => 4,		
   ), $atts));
	// Set The Query Args For This Loop
	$args = array( 
			'posts_per_page' => $limit, 
			'meta_key' => '_post_views_count', 
			'orderby' => 'meta_value_num', 
			'order' => 'DESC'
		);
	// Run The Query
	$postByViews = new WP_Query($args);
	// Check If We Have Post
	if($postByViews->have_posts()){ ?>
	<div class="ensure-popular-posts">	
	<?php
	// Foreach Post
	while ( $postByViews->have_posts() ) : $postByViews->the_post();
	?>
	<div class="single-post">
		<div class="post-thumb">
			<?php echo get_the_post_thumbnail( $postByViews->ID, 'thumbnail' ); ?>
		</div>
		<div class="post-info">
			<h3 class="post-title"><?php the_title(); ?></h3>
			<div class="post-meta">
				<div class="post-views"><?php echo ensure_get_post_views(); ?></div>	
			</div>
		</div>
	</div>	
	<?php 
	// End Of Loop	
	endwhile; ?>
	</div>	
	<?php
	} else {
		// Here You can do something if no post found.
		if(current_user_can('manage_options')){
			echo '<h4>'.__('No Post To Show Yet. Make Sure Your Post Views Are Getting Collected.','ensure').'</h4>';
			echo '<h6>'.__('Only Admins Can See This Message.','ensure').'</h6>';
		}	
	?>
		
	<?php
	}	
	wp_reset_query();
}	
/*
Register All Shorcodes At Init
*/
add_action( 'init', 'ensure_register_shortcodes');
function ensure_register_shortcodes(){
	// Registered Shortcodes
	add_shortcode ('ensure_popular_posts', 'ensure_popular_posts_build' );
};

Finishing Up The Post Views Counter Without A Plugin

You can use this page view counter in your WordPress website or plugin. If your not sure where you want to put this or decide to place it in a plugin, use our WordPress plugin generator. Share this post if you find it useful! Thanks for reading!