Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active August 29, 2015 14:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjarrett/2ecec35b53641e672743 to your computer and use it in GitHub Desktop.
Save fjarrett/2ecec35b53641e672743 to your computer and use it in GitHub Desktop.
Custom user registration process
<?php
/**
* Process user registration
*
* A custom user registration process that listens for a
* specific type POST request that will create a new user
* on the blog.
*
* @action wp
*
* @return void
*/
function fjarrett_user_registration() {
if (
'POST' !== $_SERVER['REQUEST_METHOD']
||
! isset( $_POST['registration_token'] )
||
! isset( $_POST['registration_nonce'] )
||
false === wp_verify_nonce( $_POST['registration_nonce'], 'user_registration-' . $_POST['registration_token'] )
||
! isset( $_POST['user_login'] )
||
! isset( $_POST['user_pass'] )
||
! isset( $_POST['first_name'] )
||
! isset( $_POST['last_name'] )
||
! isset( $_POST['user_email'] )
) {
return;
}
if ( is_user_logged_in() ) {
wp_die( 'Sorry, you cannot register because you are already logged in.' );
}
$user_login = sanitize_user( filter_input( INPUT_POST, 'user_login' ) );
$user_pass = filter_input( INPUT_POST, 'user_pass' ); // Unsanitized
$first_name = sanitize_text_field( filter_input( INPUT_POST, 'first_name' ) );
$last_name = sanitize_text_field( filter_input( INPUT_POST, 'last_name' ) );
$user_email = sanitize_email( filter_input( INPUT_POST, 'user_email' ) );
if (
empty( $user_login )
||
empty( $first_name )
||
empty( $last_name )
||
empty( $user_email )
||
empty( $user_pass )
) {
wp_die( 'Some required fields were missing, please try again.' );
}
$user_id = wp_create_user( $user_login, $user_pass, $user_email );
if ( is_wp_error( $user_id ) ) {
wp_die( $user_id->get_error_message() );
}
$user_args = array(
'ID' => $user_id,
'first_name' => $first_name,
'last_name' => $last_name,
'display_name' => trim( sprintf( '%s %s', $first_name, $last_name ) ),
);
$user_id = wp_update_user( $user_args );
if ( is_wp_error( $user_id ) ) {
wp_die( $user_id->get_error_message() );
}
$creds = array(
'user_login' => $user_login,
'user_password' => $user_pass,
'remember' => true,
);
$user = wp_signon( $creds, false );
if ( is_wp_error( $user ) ) {
wp_die( $user->get_error_message() );
}
wp_redirect( home_url() );
exit;
}
add_action( 'wp', 'fjarrett_user_registration' );
@fjarrett
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment