wordpress functions create user code example

Example 1: wordpress register user php

<php 
        // register
        
        $user = (isset($_POST['username']) ? $_POST['username'] : '');
        $pass = (isset($_POST['password']) ? $_POST['password'] : '');
        $email = (isset($_POST['email']) ? $_POST['email'] : '');

        if (!username_exists($user)  && !email_exists($email)) {
            $user_id = wp_create_user($user, $pass, $email);
            if (!is_wp_error($user_id)) {
                //user has been created
                $user = new WP_User($user_id);
                $user->set_role('do');
                //Redirect
                wp_redirect('URL_where_you_want_redirect');
                exit;
            } else {
                //$user_id is a WP_Error object. Manage the error
            }
        }else{
            // user exist
        }
?>

Example 2: How to create WordPress users programmatically

<?php
  global $wpdb;
 $user_id = wp_insert_user( array(
  'user_login' => "sn1",
  'user_pass' => "passwordgoeshere",
  'user_email' => "[email protected]",
  'first_name' => "sn1",
  'last_name' => 'sn1',
  'display_name' => 'sn1 sn1',
  'role' => 'editor'
));

function wp_create_users() { 
/////$meta value is store in to wp_usermeta table in database///
  $meta = array(
    'job_title' => 'developer',
    'country' => 'United States',
    'viaphp' => true
  );
 //////create user //////
    $user_login = wp_slash( "sn1" );
    $user_email = wp_slash("[email protected]" );
    $user_pass  = "passwordgoeshere";
     $userdata = compact( 'user_login', 'user_email', 'user_pass' );
    return wp_insert_user( $userdata );
  }register_activation_hook(__FILE__, 'wp_create_users' );
?>

Tags:

Sql Example