Create an admin user programmatically in WordPress - wordpress

Recently I had a client come to me to build a new website. They had also forgotten all their login details, but they did have FTP access.
How do you create an admin user programmatically in WordPress?

This will create an admin user if placed in a themes functions.php file. Please change the first three variables as needed.
/*
* Create an admin user silently
*/
add_action('init', 'xyz1234_my_custom_add_user');
function xyz1234_my_custom_add_user() {
$username = 'username123';
$password = 'pasword123';
$email = 'drew#example.com';
if (username_exists($username) == null && email_exists($email) == false) {
// Create the new user
$user_id = wp_create_user($username, $password, $email);
// Get current user object
$user = get_user_by('id', $user_id);
// Remove role
$user->remove_role('subscriber');
// Add role
$user->add_role('administrator');
}
}

Accepted answer has issues and will throw a fatal error when its run twice, because the $user_id will be empty the second time. A work around for the issue:
function rndprfx_add_user() {
$username = 'username123';
$password = 'azerty321';
$email = 'example#example.com';
if (username_exists($username) == null && email_exists($email) == false) {
$user_id = wp_create_user( $username, $password, $email );
$user = get_user_by( 'id', $user_id );
$user->remove_role( 'subscriber' );
$user->add_role( 'administrator' );
}
}
add_action('init', 'rndprfx_add_user');

Here is the queries to create a new admin user :
INSERT INTO wp_users (user_login, user_pass, user_nicename, user_email, user_status) VALUES ('newadmin', MD5('pass123'), 'firstname lastname', 'email#example.com', '0');
INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_user_level', '10');

Simply, you need to add this code sample in your functions.php:
function wpb_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'email#domain.com';
if ( !username_exists( $user ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
}
}
add_action('init','wpb_admin_account');
Do not forget to change Username, Password and Email by your own data.
here is more detailed tutorials that might help you.
How to create a new WordPress admin user programmatically

Related

Update ACF field based on user's email domain

I need some help and I can't seem to figure it out since I'm not exactly sure how to do this.
I have a custom post type called Companies. In the admin user interface, I have created an ACF relationship field to the Companies post type called user_company. Right now I am manually selecting the Companies post based on the user's email address and I would like to do this programatically.
`
function update_user_company( $user_id, $args ) {
$user = get_user_by( 'ID', $user_id );
$email = $user->user_email;
$company = get_field('user_company');
list($user, $domain) = explode('#', $args['user_email'] );
if ($domain == 'gmail.com') {
$company[] = 'Google';
update_field('user_company', $company, $post_title);
};
if ($domain == 'amyling.com') {
$company[] = 'Pearlsin Arts';
update_field('user_company', $company, $post_title);
};
}
add_action( 'user_register', 'update_user_company', 10, 2 );
`
I think your function is correct and the only thing that seems wrong is that you try to update a custom field based on a post title and you should use the post ID or in your case the user ID instead.
So you should try this:
function update_user_company( $user_id, $args ) {
$user = get_user_by( 'ID', $user_id );
$email = $user->user_email;
$company = get_field('user_company');
list($user, $domain) = explode('#', $args['user_email'] );
if ($domain == 'gmail.com') {
$company[] = 'Google';
update_field('user_company', $company, $user_id);
};
if ($domain == 'amyling.com') {
$company[] = 'Pearlsin Arts';
update_field('user_company', $company, $user_id);
};
}
add_action( 'user_register', 'update_user_company', 10, 2 );
Hope this helps

Wordpress: change user rol based in wp_usermeta value?

I need to change the user rol when a user visit any page of my site based in the value of data in database.
In my DB in the wp_usermeta has this row:
The meta_value can take the values 1 and 0.
Then, I need to add a hook to be fired when any page of the site is loaded to run a code which will change the user role to "myCustomRole" when the 'meta_value' of 'meta_key' is '1'. Something like:
add_action('template_redirect', 'hooker');
function hooker(){
$id_logged_user = $current_user_id = get_current_user_id();
$table_name = "wp_usermeta";
$results = $wpdb->get_results( "SELECT * FROM $table_name WHERE 'user_id' == $id_logged_user && 'meta_value' == 1 && 'meta_key'== 'wpuef_cid_c17');
if($results) {
$wp_user_object = new WP_User($current_user->ID);
$wp_user_object->set_role('my_custom_role');
}
}
init hook is better to update user role.
add_action('init', 'changeUserRole');
function changeUserRole()
{
$user_id = get_current_user_id();
$user_meta = get_user_meta($user_id, 'wpuef_cid_c17', true);
if ($user_meta == 1) {
$user = new WP_User( $user_id );
$user->set_role( 'my_custom_role' );
}
}

Disable password change option for specific user

How can I disable the password change option for specific user in Wordpress?
I have a user where I set a new password each week for multiple users. But some tried to change the password for this user. I don't want that - but only for this specific user profile. All the other users should be able toi change their password.
I have tried different plugins but none of them work.
Thanks a lot if you can help on this!
Add this in your function.php file
class Password_Reset_Removed
{
function __construct()
{
add_filter( 'show_password_fields', array( $this, 'disable' ) );
add_filter( 'allow_password_reset', array( $this, 'disable' ) );
}
function disable()
{
if ( is_admin() ) {
$userdata = wp_get_current_user();
$user = new WP_User($userdata->ID);
if ( !empty( $user->roles ) && is_array( $user->roles ) && $user->roles[0] == 'administrator' )
return true;
}
return false;
}
}
$pass_reset_removed = new Password_Reset_Removed();
We have just removed the fields to change password from the back-end of the WordPress. Now, some users will also try to reset the password using the Lost your password? form from the log-in page.
In order to prevent them from doing that, we will remove lost password link and disable the lost password form by adding below code
function remove_lost_your_password($text)
{
return str_replace( array('Lost your password?', 'Lost your password'), '', trim($text, '?') );
}
add_filter( 'gettext', 'remove_lost_your_password' );
function disable_reset_lost_password()
{
return false;
}
add_filter( 'allow_password_reset', 'disable_reset_lost_password');
Note - you can update userid - as per your requirements

Autologin user by email only using wordpress

I am trying to login the user using the email only (The password is checked with an API from another system). The thing is all my code is running except for the part of autologin, below is my function:
I already tried different functionalities available online but what is happening with the below code is:
1- it will let the user login, but after refresh or going to any page which requires the user to be logged it, wordpress logs the user out.
function auth_new_user($username){
if(!username_exists($username)) {
// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $username, $password, $username );
// Set the nickname
wp_update_user(
array(
'ID' => $user_id,
'nickname' => $username
)
);
// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'Subscriber' );
auto_login_usr($user_id,$username);
} // end if
else{
$the_user = get_user_by('email', $username);
$user_id = $the_user->ID;
echo $user_id;
auto_login_usr($user_id,$username);
}
}
function auto_login_usr($user_id, $username) {
$user = get_user_by( 'id', $user_id );
echo $user->user_login;
echo $user->password;
if( $user ) {
wp_set_current_user( $user_id, $user->user_login );
wp_set_auth_cookie( $user_id ,false, is_ssl());
do_action( 'wp_login', $user->user_login );
}
}
After logging in, WordPress automatically logs the user out ( keeps the user logged in for a second ). Note i debugged the code more than once and everything is appearing correctly ( User Id, User_login, and username).
Appreciate your help.
It is fine i fixed it myself, the headers was already sent. i should call the functions after_theme_setup:
either with a hook
Or Before calling get_header function

how to keep the user login for all pages in wordpress custom login function?

I am using custom login function in fuction.php for client area.But the problem is that user loges in only for one page.If user goes to another page.He has to again login and so on.
How can I keep the user login for all pages instead of one?
Also ,plz review my login function .if i am doing right?
PLZ HELP.
function login(){
global $wpdb;
if(isset($_POST['loggingg']) AND !empty($_POST['loggingg'])) {
$email = $wpdb->escape ($_REQUEST['email']);
$pass = $wpdb->escape ($_REQUEST['pass']);
$sql = $wpdb->get_results ("SELECT * FROM wp_users where user_email='$email'");
$numrows = $wpdb->num_rows;
foreach ($sql as $fsql) {
$password = $fsql->user_pass;
$user_id = $fsql->ID;
$username = $fsql->fname;
$remember = $fsql->remember;
}
if($password) {
$login_data = array();
$login_data[] = $username;
$login_data[] = $password;
$login_data[] = $remember = TRUE;
$wpdb->query ("UPDATE wp_users SET useronline='1' WHERE ID='$user_id'");
$user_verify = wp_signon ($login_data, FALSE);
wp_set_auth_cookie ($user_verify, 0, 0);
wp_set_current_user ($user_id, $username);
do_action ('wp_set_current_user');
}
else {
echo "username r password is wrong.If you forgot ur password click <a href='#'>here</a>";
}
}
}
You can use the wp signon function: Function Reference/wp signon
as you can see here:
<?php wp_signon( $credentials, $secure_cookie ) ?>
it gets and array ($credentials) and a boolean (which is optional).
here you can see a sample code it's use:
$creds = array();
$creds['user_login'] = 'username';
$creds['user_password'] = 'password';
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
echo $user->get_error_message();
this function is a core wp function, means that which means that when it's used, it will do everything the wordpress need it to do for it to work as it should.
next, you need to use WordPress Cookies.
in your case i have seen you used: Function Reference/wp set auth cookie
which is taking these parameters:
<?php wp_set_auth_cookie( $user_id, $remember, $secure ) ?>
$user_id is a integer and $remember is a boolean (true/false).
in the $user_id you tried to put a variable which is not an integer.
change it with $user_verify->ID and it should work.
I built a custom function for that for a similar project: http://cferdinandi.github.io/web-app-starter-kit/
It uses the built in login processes the WordPress uses, but from a custom page.

Resources