Building a WordPress User Login Counter Plugin

Share this article

WordPress is arguably the most popular content management system on the web.

According to Forbes, over 60 million websites globally are powered by it. Numbers like this show that WordPress is no doubt a leading contender when it comes to Content Management Systems (CMS).

A major attraction of WordPress is its large pool of plugins. Want to build an eCommerce store? There’s WooCommerce. How about a job portal? There’s WP Job Manager.

In this tutorial, we will learn how to build a plugin that counts the number of times users log in to a WordPress powered site with the login stats displayed in a custom column in user list page.

User listing with login count

Plugin Development

The majority of files in a WordPress plugin consist of PHP files, located in /wp-content/plugins/ directory. In our example, the file will be called wordpress-login-count.php. I assume you’re comfortable with connecting to your server using FTP/SFTP/SCP or SSH.

If you want to follow along, create the plugin PHP file wordpress-login-count.php. The complete plugin will be available for download at the end of this tutorial.

First off, include the plugin header. Without the header, WordPress will not recognize the plugin.

<?php

/*
Plugin Name: WordPress User Login Counter
Plugin URI: http://sitepoint.com
Description: Count the number of times users log in to their WordPress account.
Version: 1.0
Author: Agbonghama Collins
Author URI: http://w3guy.com
License: GPL2
*/

We then add a PHP namespace and create the plugin class as follows.

namespace Sitepoint\WordPressPlugin;

class Login_Counter {
// ...

All action and filter hooks required by the plugin will go into the init() method.

public function init() {
        add_action( 'wp_login', array( $this, 'count_user_login' ), 10, 2 );

        add_filter( 'manage_users_columns', array( $this, 'add_stats_columns' ) );

        add_action( 'manage_users_custom_column', array( $this, 'fill_stats_columns' ), 10, 3 );
    }

The wp_login action hook is triggered by WordPress when a user logs in, thus this is the appropriate hook for us to use to count a user log in.

The function count_user_login() below does the counting.

    /**
     * Save user login count to Database.
     *
     * @param string $user_login username
     * @param object $user WP_User object
     */
    public function count_user_login( $user_login, $user ) {

        if ( ! empty( get_user_meta( $user->ID, 'sp_login_count', true ) ) ) {
            $login_count = get_user_meta( $user->ID, 'sp_login_count', true );
            update_user_meta( $user->ID, 'sp_login_count', ( (int) $login_count + 1 ) );
        } else {
            update_user_meta( $user->ID, 'sp_login_count', 1 );
        }
    }

Code explanation: first we check if a user has an empty sp_login_count meta field.
If false, we get the previously saved login count and increment it by one (1) and if true, it therefore means the user is logging in for the first time. As a result, the value 1 will be saved against the user meta field.

The manage_users_custom_column filter for adding an additional column to the WordPress user list page is used to add a Login Count column that will output the number of times a user has logged in (see screenshot above).

The function fill_stats_columns() hooked into manage_users_custom_column adds the new column.

    /**
     * Fill the stat column with values.
     *
     * @param string $empty
     * @param string $column_name
     * @param int $user_id
     *
     * @return string|void
     */
    public function fill_stats_columns( $empty, $column_name, $user_id ) {

        if ( 'login_stat' == $column_name ) {
            if ( get_user_meta( $user_id, 'sp_login_count', true ) !== '' ) {
                $login_count = get_user_meta( $user_id, 'sp_login_count', true );

                return "<strong>$login_count</strong>";
            } else {
                return __( 'No record found.' );
            }
        }

        return $empty;
    }

Code explanation: The first if condition ensures we are actually in the login_stat column.
The next if condition checks if a login count exists for the user. If true, it returns the login count, or it returns the text No record found.

The get_instance() method creates a singleton instance of the class and then calls the init() method to register the various action and filter hooks.

Finally, we’ll make a call to the get_instance() method to put the PHP class to work.

Login_Counter::get_instance();

Voila! We are done coding our login counter plugin.

Wrap Up

To further understand how the plugin was built and to implement it in your WordPress powered website, download it from GitHub.

I hope this will be of help to you in learning how to develop plugins for WordPress.

Let us know your thoughts in the comments.

Frequently Asked Questions (FAQs) about Building a WordPress User Login Counter Plugin

How can I use the current user ID in the HTML code in any post?

To use the current user ID in the HTML code in any post, you need to use the WordPress function get_current_user_id(). This function will return the ID of the currently logged-in user. You can then use this ID in your HTML code. For example, you can use it to display a personalized message to the user. Here’s an example of how you can use it:

$user_id = get_current_user_id();
echo '<p>Welcome, user ' . $user_id . '!</p>';

Why is the wp_signon() function not working?

The wp_signon() function may not work for several reasons. One common reason is that you’re trying to use it after the headers have already been sent. This function must be called before any output is sent to the browser, otherwise, it won’t work. Another reason could be that the credentials you’re passing to the function are incorrect. Make sure that the username and password are correct and that the user exists in your WordPress database.

How can I create a login counter using PHP?

To create a login counter using PHP, you can use sessions or cookies. When a user logs in, you can increment a counter stored in a session or a cookie. Here’s a simple example using sessions:

session_start();
if (!isset($_SESSION['login_count'])) {
$_SESSION['login_count'] = 0;
}
$_SESSION['login_count']++;
echo 'You have logged in ' . $_SESSION['login_count'] . ' times.';

What is the Counter Number Showcase plugin and how does it work?

The Counter Number Showcase plugin is a WordPress plugin that allows you to display counters on your website. You can use it to display various statistics, such as the number of users, posts, comments, and so on. The plugin provides a shortcode that you can use in your posts or pages to display the counters. You can customize the appearance of the counters using the plugin’s settings.

How can I track the number of user logins in WordPress?

To track the number of user logins in WordPress, you can use the wp_login action hook. This hook is triggered whenever a user logs in. You can use it to increment a counter stored in the user’s metadata. Here’s an example:

function track_user_logins($user_login, $user) {
$login_count = get_user_meta($user->ID, 'login_count', true);
$login_count = $login_count ? $login_count : 0;
update_user_meta($user->ID, 'login_count', ++$login_count);
}
add_action('wp_login', 'track_user_logins', 10, 2);

In this example, the track_user_logins() function is called whenever a user logs in. It retrieves the current login count from the user’s metadata, increments it, and then updates the user’s metadata with the new count.

Collins AgbonghamaCollins Agbonghama
View Author

Collins is a web developer and freelance writer. Creator of the popular ProfilePress and MailOptin WordPress plugins. When not wrangling with code, you can find him writing at his personal blog or on Twitter.

ChrisBlogin counterpluginplugin developmentWordPresswordpress plugin
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week