Hello @jennyong ,
Hope you are doing well.
To check the badge level that a user has reached and assign a user role based on the badge level, you can follow these steps:
Get Badge Level:
You can use the myCred get_users_badge
function to retrieve the badge level for a specific user. Here’s an example of how you can use it:
$user_id = get_current_user_id(); // Get the current user ID $badge_id = ‘badge_id’; // Replace ‘badge_id’ with the actual ID of your badge
$badge_level = mycred_get_users_badge( $user_id, $badge_id );
In this example, ‘$badge_level’ will contain the level of the specified badge for the current user.
Assign User Role Based on Badge Level:
You can use WordPress hooks like ‘user_register’ or ‘profile_update’ to check the badge level when a user registers or updates their profile. If the user has a specific badge level, you can assign a user role using the ‘wp_update_user’ function.
Here’s an example:
function assign_role_based_on_badge_level( $user_id ) {
$badge_id = 'badge_id'; // Replace 'badge_id' with the actual ID or slug of your badge
$target_level = 3; // Replace 3 with the desired badge level for the role assignment
$badge_level = mycred_get_users_badge( $user_id, $badge_id );
if ( $badge_level >= $target_level ) {
$user = new WP_User( $user_id );
$user->add_role( 'desired_role' ); // Replace 'desired_role' with the role you want to assign
}
}
add_action( 'user_register', 'assign_role_based_on_badge_level' );
add_action( 'profile_update', 'assign_role_based_on_badge_level' );
In this example, the ‘assign_role_based_on_badge_level’ function checks if the user’s badge level is greater than or equal to the target level (3 in this case).
If it is, the user is assigned the specified role.
Let me know if you have any questions. We will help you out.
Thanks & Regards,
WP Experts Support Team