Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Display number of consecutive days a user has been active on the site

To implement an activity streak counter in WordPress, you’ll need to track user activity and update the streak counter accordingly. Below is a step-by-step guide to achieve this using custom code:

  1. Create a Custom Table: First, you’ll need a custom database table to store the activity streak information.

  2. Hook into User Activity: Use WordPress hooks to detect user activity, such as page views.

  3. Update Streak Count: Implement logic to update the streak count based on the last activity date.

  4. Display the Streak: Show the activity streak on the front end.

Step 1: Create a Custom Table

Add the following code to your theme’s functions.php file to create a custom table for storing user activity streaks. You can also place this in a custom plugin if you prefer.

function create_activity_streak_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'activity_streaks';
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE $table_name (
        user_id bigint(20) NOT NULL,
        streak int(11) NOT NULL DEFAULT 0,
        last_activity_date date NOT NULL,
        PRIMARY KEY (user_id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

add_action('after_switch_theme', 'create_activity_streak_table');

Step 2: Hook into User Activity

Hook into a common action like template_redirect to detect page views.

function update_user_activity_streak() {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        global $wpdb;
        $table_name = $wpdb->prefix . 'activity_streaks';
        
        $today = current_time('Y-m-d');
        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM $table_name WHERE user_id = %d", $user_id
        ));

        if ($row) {
            $last_activity_date = $row->last_activity_date;
            $streak = $row->streak;
            
            $date_diff = (strtotime($today) - strtotime($last_activity_date)) / (60 * 60 * 24);

            if ($date_diff == 1) {
                // Increment streak
                $streak++;
                $wpdb->update(
                    $table_name,
                    array('streak' => $streak, 'last_activity_date' => $today),
                    array('user_id' => $user_id)
                );
            } elseif ($date_diff > 1) {
                // Reset streak
                $wpdb->update(
                    $table_name,
                    array('streak' => 1, 'last_activity_date' => $today),
                    array('user_id' => $user_id)
                );
            } else {
                // Update last activity date without changing the streak
                $wpdb->update(
                    $table_name,
                    array('last_activity_date' => $today),
                    array('user_id' => $user_id)
                );
            }
        } else {
            // New entry for the user
            $wpdb->insert(
                $table_name,
                array(
                    'user_id' => $user_id,
                    'streak' => 1,
                    'last_activity_date' => $today
                )
            );
        }
    }
}

add_action('template_redirect', 'update_user_activity_streak');

Step 3: Display the Streak

Add a function to get the streak count for the logged-in user and display it on the front end.

function get_user_activity_streak($user_id) {
    global $wpdb;
    $table_name = $wpdb->prefix . 'activity_streaks';
    
    $row = $wpdb->get_row($wpdb->prepare(
        "SELECT streak FROM $table_name WHERE user_id = %d", $user_id
    ));
    
    if ($row) {
        return $row->streak;
    } else {
        return 0;
    }
}

function display_activity_streak() {
    if (is_user_logged_in()) {
        $user_id = get_current_user_id();
        $streak = get_user_activity_streak($user_id);
        echo '<p>Activity streak: ' . $streak . ' days</p>';
    }
}

add_action('wp_footer', 'display_activity_streak');

Summary

  1. Create a custom table to store user activity streaks.
  2. Hook into template_redirect to detect user activity and update the streak count.
  3. Display the activity streak on the front end for logged-in users.

With this implementation, the activity streak will be updated based on user activity and displayed on your WordPress site.

Related Posts:

  1. In Django, how do I know the currently logged-in user?
  2. Can I programmatically login a user without a password?
  3. Can’t log in: “ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.”
  4. Is there any way to rename or hide wp-login.php?
  5. How to login with email only no username?
  6. How can I redirect user after entering wrong password?
  7. Increase of failed login attempts, brute force attacks? [closed]
  8. Login page ERROR: Cookies are blocked due to unexpected output
  9. Separate registration and login for different roles
  10. SSO / authentication integration with external ‘directory service’
  11. Preventing session timeout
  12. How reduce wordpress login session timeout time?
  13. How to prefill WordPress registration with social details
  14. Check for correct username on custom login form
  15. Disallow user from editing their own profile information
  16. I can’t access my site via wp-admin
  17. ‘Password field is empty’ error when using autofill in Chrome
  18. Removing username from the ‘wordpress_logged_in’ cookie
  19. How to show ‘login error’ and ‘lost password’ on my template page?
  20. What is $interim_login?
  21. Custom login form
  22. How to prefill the username/password fields on the login page
  23. wp_signon returns user, but the user is not logged in
  24. Adding extra authentication field in login page
  25. Prevent wp_login_form() from redirecting to wp-admin when there are errors
  26. Redirect user using the ‘wp_login_failed’ action hook if the error is ’empty_username’ or ’empty_password’
  27. wp_signon() does not authenticate user guidance needed
  28. What exactly is ReAuth?
  29. What are the differences between wp_users and wp_usermeta tables?
  30. Login members using web services
  31. Make my wordpress blog remember my login “forever”
  32. How to check in timber if user is loggedin?
  33. How do I change the language of only the login page?
  34. Disable WordPress 3.6 idle logout / login modal window / session expiration
  35. Stop WordPress from logging me out (need to keep me logged in)
  36. Woocommerce registration page [closed]
  37. How to disable autocomplete on the wp-login.php page
  38. Share login data/cookies between multiple installations
  39. Synchronize WordPress user accounts across multiple domains and installations without using WordPress MU
  40. How to pass users back and forth using session data?
  41. How do I change the logo on the login page?
  42. Why does WordPress hide the reset password key from the URL?
  43. Is it possible to sign in with user_email in WordPress?
  44. How to use current_user_can()?
  45. Avoid to load default WP styles in login screen
  46. WordPress registration message
  47. How to fake a WordPress login?
  48. how to display the wordpress login and register forms on a page?
  49. Does wp_logout_url() destroy a session? (Logging out question)
  50. How can I send a welcome email to a user AFTER they login for the first time?
  51. Can not login with correct username and password
  52. Website Visible only to Registered users
  53. How can i increase the login expiration length?
  54. How do I use add_action from a class method?
  55. How to remove the WordPress logo from login and register page?
  56. How can I add a custom script to footer of login page?
  57. Brute force attack?
  58. Customize wp_new_user_notification_email()
  59. Need to execute a cron job
  60. Login email after registration never sent or received
  61. How can I create a separate blog that is private?
  62. How to keep always logged in development environment
  63. Add Confirm Password field in wp-login.php Password Reset page
  64. Track advertisement earnings per blog post and page in wordpress?
  65. Integrate recaptcha and wp_signon – what is needed?
  66. Stop users from logging in from multiple locations
  67. I want to disable E-Mail verifcation / activation when a user signs up for my WordPress site
  68. custom login page redirect to logged in user profile page
  69. Email address or username used to login in wordpress
  70. How do I check if a post is private?
  71. Front-end login: Redirect user to the post they had created
  72. Receiving “This content cannot be displayed in a frame” error on login page
  73. My login form does not work
  74. Programmatically log in a wordpress user
  75. Action wp_login_failed not working if only one field is filled out
  76. Getting “Cookies are blocked or not supported by your browser” on login page
  77. What is the purpose of logging out after WordPress upgrade?
  78. Is it alright for two people to simultaneously be logged into a WP site as administrator?
  79. wp-login.php redirecting to HTTPS
  80. Display last login time
  81. How to customise wp-login.php only for users who are setting a password for the first time?
  82. Intentionally Force Failed Login WordPress
  83. How do I turn off the ability to login?
  84. Gaining Login Access via the Database
  85. How can I test the login for an expired session?
  86. Give visitor access to password protected page/post via external script
  87. Send reset password link to user from custom lost password form
  88. How to keep track of user logins?
  89. What hooks should I use for pre-login and pre-registration actions?
  90. WordPress Login Footer URL
  91. Remove built in wordpress login and use only google auth
  92. Websites defaced by uploading script using theme editor
  93. wp_login action hook not working
  94. Make wordpress admin failed login attempt return 401
  95. Cookie settings for session across WPML subdomains using custom AJAX login
  96. How to translate “wrong password” message
  97. Login redirect_to loop with reauth=1, cookie expiry set to 1 year in past
  98. User Login Form Outside the Default wp-login Form
  99. Change sign-on URLs for security purposes
  100. Change Login Page for a Multisite Subsite
Categories login Tags google-analytics, login, statistics
Loading specific ajax from a product
How Can I Retrieve post ID in plugin file

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress