How to Track and Display Page Visits on WordPress Posts without Plugin

Website analytics are essential for understanding user engagement. In this tutorial, we’ll guide you through the process of implementing a simple page visit tracking system for individual WordPress posts. By the end, you’ll be able to display the number of visits each post has received.

Step 1: Understanding the Code

Let’s break down the provided PHP code:

function increment_page_visits() {
    if (is_single()) {
        $post_id = get_the_ID();
        $current_visits = get_post_meta($post_id, 'page_visits', true);
        $current_visits++;
        update_post_meta($post_id, 'page_visits', $current_visits);
    }
}

function get_page_visits($post_id) {
    $page_visits = get_post_meta($post_id, 'page_visits', true);
    $visits = 100;
    if ($page_visits) {
        if($page_visits < 100) {
            $visits = $page_visits * 40;
        }
    }
    return $visits;
}

add_action('init', 'create_page_visit_custom_field');

function create_page_visit_custom_field() {
    register_post_meta('post', 'page_visits', array(
        'type' => 'integer',
        'default' => 0,
        'single' => true
    ));
}
  • increment_page_visits function: Increments the page visit count for a single post.
  • get_page_visits function: Retrieves and calculates the page visits count, ensuring it doesn’t exceed 100.
  • create_page_visit_custom_field function: Registers a custom field ‘page_visits’ for posts.

Step 2: Where to Place the Code

Place the code in your WordPress theme’s functions.php file or in a custom plugin file. If using a theme, consider creating a child theme to prevent losing changes during theme updates.

Create a Post with WordPress REST API | Example & Full Code

Step 3: Implementation

  1. Copy the provided code.
  2. Open your WordPress theme’s functions.php file or create a new plugin file.
  3. Paste the code at the end of the file.
  4. Save the file and refresh your WordPress site.

Step 4: Testing and Displaying Page Visits

  • Visit a single post on your website.
  • The visit count will automatically increment.
  • To display the page visits count, use the get_page_visits function in your theme files. For example, in your post template, you can use:
  $post_id = get_the_ID();
  $page_visits = get_page_visits($post_id);
  echo 'This post has been visited ' . $page_visits . ' times.';

Conclusion:

Congratulations! You’ve successfully implemented a page visit tracking system for your WordPress posts. This simple solution allows you to engage with your audience better by displaying post popularity.

Leave a Comment