skip to Main Content

This is my code, but I only count a user in current month. How can I count a user registered every month?

global $wpdb;
    $date = getdate();
    
    $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users WHERE MONTH(user_registered) = $date[mon] AND YEAR(user_registered) = $date[year]" );
    echo esc_html("User is $user_count");

2

Answers


  1. I apologize if this doesn’t work as I’m not able to test it currently. The WHERE is setting both Month and Year from the input, causing it to only return that inputs Month & Year

    global $wpdb;
        $date = getdate();
    
        $user_count = $wpdb->get_var( "SELECT MONTH(user_registered), COUNT(*) FROM $wpdb->users WHERE YEAR(user_registered) = $date[year] GROUP BY MONTH(user_registered" );
        echo esc_html("User is $user_count");
    
    Login or Signup to reply.
  2. You should move:
    MONTH(user_registered) and YEAR (user_registered ) from WHERE to GROUP BY.
    YEAR should be in the GROUP BY otherway the result will be the count of registered may 2018 + may 2019 + may 2020 etc.

    global $wpdb;
    $date = getdate();

    $user_count = $wpdb->get_var("
    SELECT
        COUNT(*) as registered, 
        MONTH(user_registered),
        YEAR(user_registered)
    FROM users
    GROUP BY
        YEAR(user_registered), 
        MONTH(user_registered)");
    echo esc_html("User is $user_count");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search