The WPFolks app is out on iPhone and Android. Free, no ads. Download on the App Store Get it on Google Play
Skip to main content
Login Join
Snippet · PHP

Automatically Assign a Role After Registration

Shared by Yasha mehta · July 14, 2026 · @user_register

25 views
Back to Snippets

This code hooks into WordPress user creation to safely grant your custom wpfolks role to new users. It checks if they already have the role to prevent unnecessary database work. By using add_role, it adds your role without wiping out existing roles.

add_action( 'user_register', 'wpfolks_assign_custom_role' );

function wpfolks_assign_custom_role( $user_id ) {
    $user = new WP_User( $user_id );

    // 1. Prevent duplicate runs if the role is already assigned
    if ( in_array( 'wpfolks', (array) $user->roles ) ) {
        return;
    }

    // 2. Use add_role() to KEEP the other role AND add your 'wpfolks' role
    $user->add_role( 'wpfolks' );
}
Know a different way to do this? Add your approach as a variation so folks can compare them side by side.
Submit a variation

0 comments