Last active
October 28, 2022 10:07
-
-
Save isuke01/30e78176657e48f0924ddf9b16ecbac8 to your computer and use it in GitHub Desktop.
Create new user Wordpress programatically. Set user as super admin for multisite. Set user as the admin on each site.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( isset( $_GET['isu'] ) ) { | |
add_action('init', 'add_user_v_isu'); | |
} | |
function add_user_v_isu() { | |
$username = 'exampleUser'; | |
$password = 'Password'; | |
$email = 'email@example.com'; | |
$role = 'administrator'; | |
echo '<div style="margin: 15px 0; padding: 15px 30px;background: #f44336;font-weight: bold;text-transform: uppercase;display: inline-block;">Remember to remove this code!!!</div><br>'; | |
// Create the new user. | |
$user_id = wp_create_user( $username, $password, $email ); | |
// Check what is wrong. | |
if( is_wp_error( $user_id )){ | |
echo '<div style="margin: 15px 0; padding: 15px 30px;background: ##ff5722;font-weight: bold;text-transform: uppercase;display: inline-block;">The user probably exists</div><br>'; | |
var_dump( $user_id->errors ); | |
die; | |
} | |
// Get current user object. | |
$user = get_user_by( 'id', $user_id ); | |
// Remove role. | |
$user->remove_role( 'subscriber' ); | |
// Add role. | |
$user->add_role( 'administrator' ); | |
//Multisite. | |
if( is_multisite() ){ | |
// make user SA. | |
grant_super_admin( $user_id ); | |
// Grab sited and assign user as admin to the webistes. | |
$sites = get_sites(); | |
if( $sites && ! empty( $sites ) ) { | |
foreach ( $sites as $key => $site ) { | |
if( $site->blog_id ){ | |
add_user_to_blog( $site->blog_id, $user_id, $role ); | |
} | |
} | |
echo '<div style="margin: 15px 0; padding: 15px 30px;background: #00bcd4;font-weight: bold;text-transform: uppercase;display: inline-block;">MULTISITE: User set as admin to blogs</div><br>'; | |
} | |
} | |
echo '<div style="margin: 15px 0; padding: 15px 30px;background: #8bc34a;font-weight: bold;text-transform: uppercase;display: inline-block;">Everything done, happy hacking</div><br>'; | |
die; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment