HummingbirdUK main logo

Coding solutions to business problems

About us

We use code to create solutions to business challenges, bottle-necks and headaches.

If you think your business has a problem that can be solved through code, we are happy to chat things through without any obligation.

Get in touch

Create new Wordpress user with script (1)

Home / Blog / Create new Wordpress user with script (1)

Written by Giles Bennett

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.

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!

Author : Giles Bennett

About the author

Giles Bennett built his first website in 1996, and is old enough to miss Netscape Navigator. Initially a lawyer, he jumped ship to IT in 2008, and after 5 years as a freelancer, he founded HummingbirdUK in 2013. He can be reached by email at giles@hummingbirduk.com.