Count WordPress Post View

How to Count WordPress Post Views Programmatically Without a Plugin

  • December 19, 2023
  • in Web Tech
  • by AW Bali Digital

WordPress is a versatile and powerful content management system (CMS) that powers a significant portion of the internet. While there are numerous plugins available for tracking post views, sometimes you may prefer a lightweight and customized solution. In this article, we will explore how to count WordPress post views programmatically without relying on a plugin.

Step 1: Create a Custom Field to Store Views First, you need to create a custom field to store the view count for each post. Open your theme’s functions.php file and add the following code:

function custom_post_views() {
    $count = get_post_meta(get_the_ID(), 'post_views', true);
    $count = $count ? $count : 0;
    return $count;

function increment_post_views() {
    $count = get_post_meta(get_the_ID(), 'post_views', true);
    $count = $count ? $count : 0;
    update_post_meta(get_the_ID(), 'post_views', $count);

The custom_post_views function retrieves the current post views, and the increment_post_views function increments the count and updates the custom field.

Step 2: Display the Post Views Count Now that you have a mechanism to store and update post views, you can display the count on your posts. Open your theme’s single.php file and add the following code where you want to show the view count:

<p>Views: <?php echo custom_post_views(); ?></p>

This code snippet fetches and displays the post views count.

Step 3: Ensure Incrementation on Post Views To increment the count every time a user visits a post, you need to call the increment_post_views function. Open your theme’s single.php file and add the following code within the loop:

if (have_posts()) :
while (have_posts()) : the_post();
// ... rest of your post content

This ensures that the post views are incremented each time a user views the post.

Conclusion: By following these steps, you can easily implement a programmatic solution to count WordPress post views without relying on plugins. This lightweight approach allows you to have more control over the functionality and ensures that your site remains efficient and responsive. Customize the code further to suit your specific needs and enhance the user experience on your WordPress website.

AW Bali Digital

© 2024 by PT BIKIN INOVASI TEKNOLOGI, All Rights Reserved.