Let New Users Pick an Account Type
Adds an "I am signing up as" choice to the registration form that gives the new account one of the roles you allow, for example Reader or Writer.
Opens WPIDE on
Code
// Role ID => label shown on the form. The first one is the default.
$wpide_signup_roles = array(
'subscriber' => 'Reader',
'contributor' => 'Writer',
);
$wpide_safe_roles = function () use ( $wpide_signup_roles ) {
$danger = array( 'manage_options', 'edit_users', 'promote_users', 'activate_plugins', 'edit_others_posts', 'unfiltered_html' );
$safe = array();
foreach ( $wpide_signup_roles as $role => $label ) {
$object = get_role( $role );
if ( $object && ! array_intersect( $danger, array_keys( array_filter( $object->capabilities ) ) ) ) {
$safe[ $role ] = $label;
}
}
return $safe;
};
add_action( 'register_form', function () use ( $wpide_safe_roles ) {
$roles = $wpide_safe_roles();
$current = isset( $_POST['wpide_signup_role'] ) ? sanitize_key( $_POST['wpide_signup_role'] ) : key( $roles );
if ( count( $roles ) < 2 ) {
return;
}
echo '<fieldset style="margin-bottom:16px"><legend>I am signing up as</legend>';
foreach ( $roles as $role => $label ) {
printf( '<label style="display:block"><input type="radio" name="wpide_signup_role" value="%1$s" %2$s> %3$s</label>', esc_attr( $role ), checked( $current, $role, false ), esc_html( $label ) );
}
echo '</fieldset>';
} );
add_action( 'register_new_user', function ( $user_id ) use ( $wpide_safe_roles ) {
$role = isset( $_POST['wpide_signup_role'] ) ? sanitize_key( $_POST['wpide_signup_role'] ) : '';
if ( $role && array_key_exists( $role, $wpide_safe_roles() ) ) {
( new WP_User( $user_id ) )->set_role( $role );
}
} );
Notes
Roles that can manage options, users, plugins or other people's posts are refused even if you list them, so the form can never hand out admin rights.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.