Is there a way to change back the user role after x
days? When people register at my site, they have an 2 options to choose: seller
or customer
. I want to put an additional user role member1
, and if I make them user role member1
, after 14 days the user role should automatically change back to their default user role (either seller
or customer
). Is this possible?
1 Answer
Here is an idea that you can implement. I think it will work just fine.
- Save the expiration time in user meta. Say the meta name is
change_role
. What you save in the meta is unix time. If you want to change them back in 14 days. Set the meta value totime() + 60 * 60 * 24 *14
code example update_user_meta($user_id, 'change_role', time() + 60 * 60 * 24 *14);
- Register a wp cron to search for expired accounts and change their roles back. Run the cron every hour or so. The search query will search for users who have the
change_role
meta value less then the current unix timestamp value.
Code Example
The cron function may look like this.
function change_expired_users_role(){
$args = array(
'meta_key' => 'change_role',
'meta_value' => time(),
'meta_compare' => `<=`,
'fields' => array('ID')
);
$users = get_users($args);
if(empty($users))
return;
foreach($users as $user){
// change user role
// delete the user meta
}
}
Hope this helps.