WordPress
Article

Building a WordPress User Login Counter Plugin

By Agbonghama Collins

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.

  • http://www.cygnet-infotech.com/ Hemang Rindani

    Nice information. WordPress is one of the easiest and efficient enterprise web content management system that can handle any business requirements effortlessly and allow a developer to design some powerful websites. The modules and themes are available for virtually everything and developer can use it by simply downloading and installing them to the core directory. WordPress plugins add tremendous power and value to the websites. From providing the basic structure to maintaining security of multiple websites, plugins are pretty capable and handy tool. User Login statistics is an efficient plugin that can be used to get real-time login count details. A simple addition of field named Login_count in database can also be a useful way to count the number of times a particular user is logged-in. Make sure to identify and use authorized tools that does not compromise website security.

    • Suzanne Lewis

      I am getting a salary of more than 3900 dollars each week , that is awesome. Over a year ago I was in a horrible condition , jobless and Bank account with only few bucks . Thank one of my friends showed me a way where I was able to gather my self and making average of 85 d/h. So it can change your life as it has changed mine.

      coolmath.CO.NF

      ert…

      • http://www.cygnet-infotech.com/ Hemang Rindani

        Truly WordPress is a great platform. Congratulations on your amazing career.

  • http://tellado.es/ Fernando

    Nice code but …

    When I try to activate it I receive a fatal error from WordPress, this one:

    Fatal error: Can’t use function return value in write context in /xxx/xxxx/xxxxxxxx/wp-content/plugins/WordPress-User-Login-Counter-master/wordpress-login-count.php on line 33

    • http://w3guy.com Agbonghama Collins

      Apparently you are using a PHP version lesser than 5.5

      Change this line

      if ( ! empty( get_user_meta( $user->ID, 'sp_login_count', true ) ) ) {

      To

      $count = get_user_meta( $user->ID, ‘sp_login_count’, true );
      if ( ! empty( $count ) ) {

  • Gazi Salah Uddin

    thanks for sharing!

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Instant Website Review

Use Woorank to analyze and optimize your website to improve your website to improve your ranking!

Run a review to see how your site can improve across 70+ metrics!

Get the latest in WordPress, once a week, for free.