- This topic has 1 reply, 1 voice, and was last updated 2 months ago by
Luis Paulo Lohmann.
Viewing 2 posts - 1 through 2 (of 2 total)
-
AuthorPosts
-
April 1, 2025 at 6:43 pm #142847
Luis Paulo Lohmann
ParticipantI’m importing users from a Windows AD directory and would like to assign secondary roles based on a meta field.
I tried adding a hook in functions.php and seemingly the roles are being added to the database, but not showing up in the editor front-end.
Could you please help me? Here’s the code:
function assign_secondary_role($user_id) { // Retrieve the secondary role from user meta $secondary_role = get_user_meta($user_id, 'user_depto', true); // Map the secondary role to its role key $role_mapping = [ 'T.i.' => 'ti', 'Diretoria Executiva' => 'diretoria_executiva', 'Marketing' => 'marketing' ]; if (isset($role_mapping[$secondary_role])) { // Get existing roles $existing_roles = get_user_meta($user_id, 'wpfront_urole_secondary', true); if (!is_array($existing_roles)) { $existing_roles = []; } // Add the new secondary role $existing_roles[] = $role_mapping[$secondary_role]; update_user_meta($user_id, 'wpfront_urole_secondary', $existing_roles); // Ensure roles are refreshed properly delete_user_meta($user_id, '_wpfront_user_role_cache'); // Clear WPFront cache clean_user_cache($user_id); // Clear WP cache // Force WPFront to reapply the role do_action('wpfront_user_role_update', $user_id); // Manually refresh user roles $user = new WP_User($user_id); $user->get_role_caps(); // Force reload of capabilities error_log("Assigned roles after update: " . print_r(get_user_meta($user_id, 'wpfront_urole_secondary', true), true)); error_log("Secondary role '{$role_mapping[$secondary_role]}' assigned to user ID {$user_id}."); } else { error_log("No secondary role found for user ID {$user_id}."); } } // Hook into user profile update add_action('profile_update', function($user_id) { assign_secondary_role($user_id); });
April 2, 2025 at 10:35 pm #142861Luis Paulo Lohmann
ParticipantTo whom might have the same question, I followed Mr. Mohan’s instructions and used the native WP add_role method:
https://developer.wordpress.org/reference/classes/wp_user/add_role/
-
AuthorPosts
Viewing 2 posts - 1 through 2 (of 2 total)
- You must be logged in to reply to this topic.