Create new user in WordPress programmatically (1)

A number of times have cropped up where I’ve got FTP or SFTP access to a WP installation, but no username or password details. Rather than wait for the client to reply, it’s often easier to just create a new user in WordPress programmatically. There are a number of different methods of doing this, and I’ll deal with them in a sporadic series of posts.

Method 1


The easiest method (in my view) involves editing the theme’s functions.php file to add a small one-off function that creates the user, then makes them an admin.

To use this method, simply download your theme’s functions.php file, and create a backup copy of it (you’ll need it later).

Then insert the script below into the very bottom of it, before the closing ?> php tag. Be sure to replace the $username, $password and $email variables with your chosen values.

add_action('init', 'create_a_user');
    function create_a_user() {
        $username = 'username';
        $password = 'password';
        $email = 'your@emailaddress.com';
        $user_id = wp_create_user( $username, $password, $email );
        $user = get_user_by( 'id', $user_id );
        $user->remove_role( 'subscriber' );
        $user->add_role( 'administrator' );
}

Upload it in place of the existing functions.php, then visit any page on your WordPress installation – it doesn’t matter which one. Then – and this is important – remove that code from your functions.php as otherwise WordPress’ll try to create the new user every time someone visits a page, and it’ll fall over (because the user has already been created). Then log in using the details that you put in the script, and you’re done!

One comment

  • Lewis

    Depending on your WP you might find this code causes issues. The problem seems to be this line: $user = get_user_by( ‘id’, $user_id );
    You can make it work again by replacing it with $user = get_user_by( ’email’, $email ); – some versions of WP don’t return a user ID nicely it seems.

Leave a Reply

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

Want to talk to us about your project?