0

I imported 4000 users on 1st October 2015 as "subscribers" and now need to change all their roles to a custom role called "To Be Approved". So what I need is to change the roles of these subscribers to my custom role of "To Be Approved" only if they registered on 1st October. I'm using this plugin to filter the date they registered in the dashboard - https://wordpress.org/plugins/recently-registered/ and this plugin https://wordpress.org/plugins/user-role-editor/ for my custom role called "To Be Approved". It is taking time to manually change their roles in the dashboard. I have used the code below to start me off but am a newbie with PHP. Any help would be appreciated:

// Access to get_users
$blogusers = get_users( 'subscriber' );

foreach ($blogusers as $user) {

$date = '2015-10-01';
$registered = ($user_info->user_registered);

if($date == $registered) {
    $u = new WP_User( $user->ID );

    // Remove role
    $u->remove_role( 'subscriber' );

    // Add role
    $u->add_role( 'to_be_approved' );
}

}

Am I on the right track with this?

Thanks

  • Update subscribers to To Be Approved with an sql-script? – bestprogrammerintheworld Nov 3 '15 at 12:02
  • Could do. Thought I was close enough with this PHP script though. I tested without the date condition and all worked fine. Just need to factor the date into this now.. – sc2015 Nov 3 '15 at 16:39
1

Close, your date comparison is slightly off - user_registered will be a MySQL datetime, so your string comparison will never evaluate true. Instead, convert it to just the date:

$registered = mysql2date( 'Y-m-d', $user->user_registered ); 

Now we're talking:

if ( '2015-10-01' === $registered ) {
    // chocks away
}

Update: Here's a complete snippet that should be less intensive on memory too:

$users = get_users(
    array(
        'fields' => array( 'ID', 'user_registered' ),
        'role'   => 'subscriber',
    )
);

foreach ( $users as $user ) {
    if ( '2015-10-01' === mysql2date( 'Y-m-d', $user->user_registered ) ) {
        $u = new WP_User( $user->ID );

        // Remove role
        $u->remove_role( 'subscriber' );

        // Add role
        $u->add_role( 'to_be_approved' );
    }
}

Code is not tested and you should assume it will be break, so backup, backup, backup. Make sure you have debugging enabled too.

  • Thanks TheDeadMedic but no joy I'm afraid :( – sc2015 Nov 3 '15 at 16:31
  • My bad - I lifted your variable names without checking them. You should have debugging enabled to avoid problems like this in the future! – TheDeadMedic Nov 3 '15 at 17:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.