The can_add_user_to_blog WordPress PHP filter determines whether a user should be added to a site.
Usage
add_filter('can_add_user_to_blog', 'my_custom_can_add_user_to_blog', 10, 4); function my_custom_can_add_user_to_blog($retval, $user_id, $role, $blog_id) { // your custom code here return $retval; }
Parameters
$retval
(true|WP_Error): True if the user should be added to the site, error object otherwise.$user_id
(int): User ID.$role
(string): User role.$blog_id
(int): Site ID.
More information
See WordPress Developer Resources: can_add_user_to_blog
Examples
Prevent users with a specific role from being added
Prevents users with the role “restricted” from being added to the site.
add_filter('can_add_user_to_blog', 'prevent_restricted_role', 10, 4); function prevent_restricted_role($retval, $user_id, $role, $blog_id) { if ($role === 'restricted') { return new WP_Error('restricted_role', 'Users with the restricted role cannot be added.'); } return $retval; }
Limit users to a specific blog
Allows users to be added only to the blog with an ID of 2.
add_filter('can_add_user_to_blog', 'limit_users_to_blog_2', 10, 4); function limit_users_to_blog_2($retval, $user_id, $role, $blog_id) { if ($blog_id != 2) { return new WP_Error('not_allowed', 'Users can only be added to blog ID 2.'); } return $retval; }
Restrict user addition based on email domain
Prevents users with an email address from a specific domain from being added to the site.
add_filter('can_add_user_to_blog', 'restrict_email_domain', 10, 4); function restrict_email_domain($retval, $user_id, $role, $blog_id) { $user = get_user_by('id', $user_id); $email_domain = '@restricted.com'; if (strpos($user->user_email, $email_domain) !== false) { return new WP_Error('restricted_email_domain', 'Users with this email domain cannot be added.'); } return $retval; }
Only allow administrators to add users
Allows only users with the administrator role to add new users to the site.
In this example, the user with an ID of 123 will always be allowed to be added to any blog, regardless of other restrictions that might be in place.
add_filter('can_add_user_to_blog', 'only_admins_can_add_users', 10, 4); function only_admins_can_add_users($retval, $user_id, $role, $blog_id) { if (!current_user_can('administrator')) { return new WP_Error('not_allowed', 'Only administrators can add users.'); } return $retval; }
Allow a specific user to be added to all blogs
Always allows a user with a specific ID to be added to any blog.
add_filter('can_add_user_to_blog', 'allow_user_to_all_blogs', 10, 4); function allow_user_to_all_blogs($retval, $user_id, $role, $blog_id) { $allowed_user_id = 123; if ($user_id == $allowed_user_id) return true; return $retval; }