Sometimes it is needed to create WP user php on a WordPress site. So that’s I’m going to write about this here.
I’ve divided this into two sections.
-
- How to create a user in a Theme.
- How to create a user in a plugin.
How to create WP user php.
we’ll need to use ‘after_setup_theme’ hook for that.
add_action(‘after_setup_theme’, ‘themeprefix_create_a_user’); function themeprefix_create_a_user() { // let’s define some variable $user_name = ‘webextent’; $password = ‘strong-pass-recommended’; $email = ‘noreply@webextent.net’; // let’s check if this user already exists or not, if not then pass If ( ! username_exists( $user_name ) ) { // wp_create_user() to create a user $user_ID = wp_create_user( $user_name, $password, $email ); // pass $user_ID to WP_User class $user = new WP_User( $user_ID ); // define a role for the user $user->role( ‘administrator’); //you can use editor/author/contributor/subscriber } }
Note : Most importantly update $user_name, $password and $email as your need. And delete the file after creating the user. And paste this code in functions.php
How to create a user from a plugin ( or a create MU plugin )
Let’s talk about how to create an MU ( must use ) plugin.
First of all, create a folder in wp-content/ called ‘mu-plugins’
Then create a ‘.php’ file in the folder, you can name it whatever you want.
But let’s name it ‘manage-users.php’ ( for example )
Then open the file in an editor
Certainly, we will use ‘init’ hook to create a user in our MU plugin
And follow the code below :
add_action(‘init’, ‘themeprefix_create_a_user’); function themeprefix_create_a_user() { // let’s define some variable $user_name = ‘webextent’; $password = ‘strong-pass-recommended’; $email = ‘noreply@webextent.net’; // let’s check if this user already exists or not, if not then pass If ( ! username_exists( $user_name ) ) { // wp_create_user() to create a user $user_ID = wp_create_user( $user_name, $password, $email ); // pass $user_ID to WP_User class $user = new WP_User( $user_ID ); // define a role for the user $user->role( ‘administrator’); //you can use editor/author/contributor/subscriber } }
Note: similarly we can use this method in any existing plugin as well.
You can check out WordPress Roles and Capabilities here
Tags: create a user with php create wp user programatically create a user wordpress
0 comments