🤯 50% Off! 700+ courses, assessments, and books

Building a WordPress User Login Counter Plugin

Collins Agbonghama
Share

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.