Back to all posts

How to Create a WordPress Plugin for Counting User Visits to Your Site


Do you want to keep track of how many visitors your WordPress site receives? Maybe you want to know how popular your site is or how your traffic is changing over time. Whatever your reasons, you can use a WordPress plugin to count the number of visitors to your site.

In this post, we’ll show you how to create a plugin that counts the number of times each user visits your site. This will allow you to track individual user visits and see how often each user returns to your site.

To get started, create a new plugin by creating a new directory in the WordPress plugins directory and adding a PHP file (visiter_counter.php) with the following code:

<?php
/*
Plugin Name: CSP User Counter
Plugin URI: chethanspoojary.com
Description: This plugin counts user visits to your website
Version: 1.0
Author: Chethan S Poojary
Author URI: https://sentensecase.com/
*/

// Create a function to count not logged in user
function user_visit_counter() {
   
        session_start();
        $count_key = 'visitor_visit_count';
        $count = get_option( $count_key, 0 );
        if ( !isset( $_SESSION['visitor_id'] ) ) {
            $count++;
            update_option( $count_key, $count );
            $_SESSION['visitor_id'] = uniqid();
        }
        echo '<p>Total Number of visitor till date ' . $count . '.</p>';
}

// Create a function to count logged in user
function logedin_user_visit_counter() {
    // Check if user is logged in
      if ( is_user_logged_in() ) {
        $user_id = get_current_user_id();
        $count_key = 'user_visit_count';
        $count = get_user_meta( $user_id, $count_key, true );
        if ( $count == '' ) {
            $count = 0;
            update_user_meta( $user_id, $count_key, '0' );
        } else {
            $count++;
            update_user_meta( $user_id, $count_key, $count );
        }
        echo '<p>You have visited this site ' . $count . ' times.</p>';
    }
}

// Add a shortcode to display the user visit count on any page or post
function user_visit_count_shortcode() {
    ob_start();
    user_visit_counter(); // not logged in user count function call
	logedin_user_visit_counter(); //logged in user function call
    return ob_get_clean();
}

add_shortcode( 'user_visit_counter', 'user_visit_count_shortcode' );

/**
 * Please use [user_visit_counter] shortcode in your frontend 
 */

?>

To use this plugin, simply copy the code into a new file and save it as visiter_counter.php. Then upload the file to the wp-content/plugins directory on your WordPress site. Finally, activate the plugin from the WordPress dashboard. You can then use the ‘[user_visit_counter]’ shortcode to display the user’s visit count on any page or post.