Are you looking for a way to track post views without a plugin using post meta? While there’s probably a plugin for this, we have created a quick code snippet that you can use to track post views without a plugin using post meta in WordPress.

Instructions:

Add this code to your theme’s functions.php file or in a site-specific plugin:

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 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); } } // Remove issues with prefetching adding extra views remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Optionally add this code as well to a column in the WordPress admin that displays the post views:

// Add to a column in WP-Admin add_filter('manage_posts_columns', 'posts_column_views'); add_action('manage_posts_custom_column', 'posts_custom_column_views',5,2); function posts_column_views($defaults){ $defaults['post_views'] = __('Views'); return $defaults; } function posts_custom_column_views($column_name, $id){ if($column_name === 'post_views'){ echo getPostViews(get_the_ID()); } }

This part of the tracking views code will set the post views. Just place this code below within the single.php file inside the WordPress Loop.

<?php setPostViews(get_the_ID()); ?>

Note about fragment caching: If you are using a caching plugin like W3 Total Cache, the method above to set views will not work as the setPostViews() function would never run. However, W3 Total Cache has a feature called fragment caching. Instead of the above, use the following so the setPostViews() will run just fine and will track all your post views even when you have caching enabled.

<!-- mfunc setPostViews(get_the_ID()); --><!-- /mfunc -->

The code below is optional. Use this code if you would like to display the number of views within your posts. Place this code within the Loop.

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

Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.

If you liked this code snippet, please consider checking out our other articles on the site like: 10 best WordPress testimonial plugins and how to Set Up Author Tracking in WordPress with Google Analytics.