How to add new user in WordPress with Administrator Level using code in functions.php

This is a basic requirement for some developer. Just copy and paste below code and replace the appropriate details like username, email and password in functions.php. After that just run the website.

add_action('init', 'add_my_user');
function add_my_user() {
    $username = 'Username Here';
    $email = 'Email ID Here';
    $password = 'Password Here';

    $user_id = username_exists( $username );
    if ( !$user_id && email_exists($email) == false ) {
        $user_id = wp_create_user( $username, $password, $email );
        if( !is_wp_error($user_id) ) {
            $user = get_user_by( 'id', $user_id );
            $user->set_role( 'administrator' );
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *