Getting users who registered 360 days from current date

As per the title, what I want to do is run a custom query that (using WP-Cron) will run once a day to check for users who registered exactly 360 days before the current date (don’t need time, just date) and gather their ID. I have this:

global $wpdb;
$sql = $wpdb->prepare(
    "SELECT * FROM {$wpdb->users} 
     WHERE {$wpdb->users}.user_registered = CURRENT-DATE-MINUS-360-DAYS";
);
$userdata = HOW-DO-I-GET-THE-RESULTS-IN-AN-ARRAY

Where the bit in caps represents the bit I have no idea what to do 🙂 Any help much appreciated.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I peeked into the WP_User_Query class and it supports a WP_Date_Query query on the user registration date.

So we could use:

$query = new WP_User_Query( $args );

or simply:

$users = get_users( $args );

where:

$args = [
    'fields'     => 'ID',
    'number'     => 8,
    'date_query' => [
        [ 'before' => '359 days ago midnight' ],
        [ 'after'  => '360 days ago midnight', 'inclusive' => true ],
   ] 
];

This generates the following SQL query (expanded view):

SELECT wp_users.ID 
    FROM wp_users 
    WHERE 1=1 
        AND ( 
                wp_users.user_registered >= '2014-08-10 00:00:00' 
            AND       
                wp_users.user_registered < '2014-08-11 00:00:00' 
        ) 
    ORDER BY user_login ASC 
    LIMIT 10;

where today is 2015-08-05.

It looks like we should update the Codex on get_users() function, regarding the date_query argument.

Method 2

Use

$wpdb->get_results("SELECT *, (DATEDIFF(NOW(),user_registered)) AS daydiff FROM {$wpdb->users} WHERE 'daydiff' = 360");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x