wordpressnonce

WordPress: wp_create_nonce() not creating a value inside custom plugin


I am creating a custom plugin for user registration with the following steps:

A function to create my HTML form fields

function render_registration_form() {
   ob_start();
   ...
   <input type="hidden" id="register_nonce" name="register_nonce" value="<?php wp_create_nonce('generate-nonce'); ?>" />
   //Above line does not create a nonce at all
   ...
   return ob_get_clean();
}

A function to use as shortcode to display the above form

function custom_user_registration_form() {
   //Render registration form only if user is not logged in already!
   if(!is_user_logged_in()) {
       $registration_enabled = get_option('users_can_register');
       if($registration_enabled) {
           $output = render_registration_form(); (written above)
       } else {
           $output = __('User registration is not enabled');
       }

       return $output;
   } else {
       return _e('You are already logged in!');
   }
}

add_shortcode('register-user', 'custom_user_registration_form');

A function to validate and add a new user along with meta to the database:

function validate_and_create_user() {
   if(isset($_POST['txt_username']) && wp_verify_nonce($_POST['register_nonce'], 'register-nonce')) {
   $user_data = array(
     'user_login' => $loginid,
     'user_pass' => $password,
     'user_nicename' => $first_name,
     'display_name' => $first_name . ' ' . $last_name,
     'user_email' => $email,
     'first_name' => $first_name,
     'last_name' => $last_name,
     'user_registered' => date('Y-m-d H:i:s'),
     'role' => 'subscriber'
     );

     $new_user_id = wp_insert_user($user_data);

     ...
}

add_action('init', 'validate_and_create_user');

Since no nonce value is getting created inside the form the check wp_verify_nonce($_POST['register_nonce'], 'register-nonce') always fails and no user data is getting saved in the database.

According to https://codex.wordpress.org/Pluggable_Functions:

Pluggable functions are no longer being added to WordPress core. All new functions instead use filters on their output to allow for similar overriding of their functionality.

I am new to WordPress. How can I solve this?


Solution

  • Try This:

    wp_nonce_field('register_nonce');
    

    in the place of input.

    And for retrieving nonce use following

    $retrieved_nonce = $_REQUEST['_wpnonce'];
    if (!wp_verify_nonce($retrieved_nonce, 'register_nonce')) die( 'Failed security check' );