Best way to create a user programatically

I want to create a user via a standalone script. I want an activation email to be sent out, in the same way that it is when a user is created from the Add User screen. An email is set out with a link to create the password. There is no password in the email.

There seem to be various functions for creating new users.

There's also

  • wp-admin/user-new.php

Below is the code I have. It creates a new user, but it isn't the notification email. I've checked that wp-mail() and php mail() are working correctly.

I'm not sure that this is the right direction. I feel there might be an easier way to do it. If this is the right direction, any pointers on why the notification is not being sent?

Thanks.

?php
define( 'SHORTINIT', true );
require_once( '/var/www/html/mysite/wp-load.php' );
require_once ('/var/www/html/mysite/wp-includes/user.php');
require_once ('/var/www/html/mysite/wp-includes/formatting.php');
require_once ('/var/www/html/mysite/wp-includes/capabilities.php');
require_once ('/var/www/html/mysite/wp-includes/pluggable.php');
require_once ('/var/www/html/mysite/wp-includes/kses.php');
require_once ('/var/www/html/mysite/wp-includes/meta.php');
function __() {}
wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );
wp_new_user_notification ( testuser8,null,'both' );
?

Topic wp-create-user scripts php email user-registration Wordpress

Category Web


Use WP-CLI's User Create and put in a script.

wp user create - Create a user.

$ wp user create testuser8 [email protected] --user_pass=apsswd--role=author --send-email
Success: Created user 3.

You should read the codex page re wp_create_user.

You don't describe the context in which your code runs. You shouldn't need all those require_once calls.

Anyhow, in this line wp_new_user_notification ( testuser8,null,'both' ); what is testuser8 ? It's not a variable, it's not a string, it's just some text that probably throws an error.

Try:

$user_id = wp_create_user ( 'testuser8', 'apsswd', '[email protected]' );
if( is_wp_error( $user_id ) ) 
    var_dump( $user_id );
else
    wp_new_user_notification ( $user_id, null,'both' );

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.