Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.