Assigning roles automatically by birthdate

[ad_1]

Hey, I’m building a community site. I created two custom roles – one for over 18 years old, one for under 18 years old. I want the roles to be automatically assigned during registration – on the registration form, I have a birthdate field, and I want it to calculate age and which category. So far, my coding looks like:

// Function to calculate age from birthdate
function calculate_age($birthdate) {
$birthdate = strtotime($birthdate); // Assuming YYYY-MM-DD format
$now = time();
$age = date(‘Y’, $now) – date(‘Y’, $birthdate);
return $age – ((date(‘md’, $now) < date(‘md’, $birthdate)) ? 1 : 0);
}

// Action hook on user registration
add_action(‘user_register’, ‘assign_role_by_birthdate’);

function assign_role_by_birthdate($user_id) {
$birthdate = get_user_meta($user_id, ‘date_box_1711754761_field’, true);
$age = calculate_age($birthdate);

if ($age >= 18) {
$role = ‘plotter’; // Replace with your actual role name (case-sensitive)
} else {
$role = ‘plotterini’; // Replace with your actual role name (case-sensitive)
}

$user = new WP_User($user_id);
$user->set_role($role);
}

But it’s not working. Am I just completely offbase?

I’ve tried looking for a plugin that can do this, but haven’t found one that will assign role by age.

Even better, would be if it will later change roles when people age up to 18, but I can cross that bridge later if need be.

Help! please!

[ad_2]

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer