arrow_back
Back

WordPress users: roles, capabilities, authentication, and user meta

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

Add a new user:

$user_id = wp_insert_user( [
    'user_login'    => sanitize_user( $username ),
    'user_email'    => sanitize_email( $user_email ),
    'user_pass'     => wp_generate_password(),
    'role'          => 'wp_job_board_pro_employer',
] );

Example from one theme:

$username = sanitize_title( $employer_name );

if ( strlen( $username ) > 60 ) {
    $username = substr( $username, 0, 60 );
}

if ( username_exists( $username ) ) {

    $username .= '_' . rand( 10000, 99999 );

    if ( username_exists( $username ) ) {
        $username .= '_' . rand( 10000, 99999 );
    }
}

$user_email = $username . '@fakeuser.com';

if ( email_exists( $user_email ) ) {
    $user_email = $username . '_' . rand( 10000, 99999 ) . '@fakeuser.com';

    if ( email_exists( $user_email ) ) {
        $user_email = $username . '_' . rand( 10000, 99999 ) . '_' . rand( 10000, 99999 ) . '@fakeuser.com';
    }
}

Roles and capabilities

open_in_new Roles and Capabilities .

Roles

Adding a role:

add_role( 'marketer', 'Marketer', [
    'read' => true,
] );

Removing a role:

remove_role()

Capabilities

add_cap()
remove_cap() 

open_in_new https://www.role-editor.com/woocommerce-admin-bar-access/

code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

WordPress meta boxes: add_meta_box, save_post, and post meta

arrow_forward