0

[SOLVED]

I have a custom registration form that will have the regular WordPress fields, and some extra ones.

I need the user role to be set to 'lojas' when the user clicks the submit button.

Everything works, but the role gets registered as the regular 'subscriber'.

Here is part of my code [UPDATED]:

add_role( 'loja', 'Loja', array( 'read' => true, 'level_0' => true ) );
function ds_registration_form(&$fields_user, &$errors) {

  // Check args and replace if necessary
  if (!is_array($fields_user))     $fields_user = array();
  if (!is_array($fields_loja))     $fields_loja = array();
  if (!is_wp_error($errors))  $errors = new WP_Error;

  // Check for form submit
  if (isset($_POST['submit_loja'])) {

// Get fields from submitted form
$fields_loja = ds_get_fields_loja();

// Validate fields and produce errors
if (ds_validate_loja($fields_loja, $errors)) {

  // If successful, register user
  $loja_id = wp_insert_user($fields_loja);

  update_user_meta( $loja_id, 'teste', $fields_loja['teste'] );
$loja_id->add_role( 'loja', 'Lojas');
  if( ! is_wp_error( $loja_id ) ) {
    $user_wp = new WP_User( $loja_id );
    $user_wp->add_role( 'lojas');
  }

  // And display a message
  echo 'Registration complete. Goto <a href="' . get_site_url() . '/wp-login.php">login page</a>.';

  // Clear field data
  $fields_loja = array(); 
}

  }
  // Santitize fields
  ds_sanitize_user($fields_user);

  // Generate form
  ds_display_form_user($fields_user, $errors);

  // Santitize fields
  ds_sanitize_loja($fields_loja);

  // Generate form
  ds_display_form_loja($fields_loja, $errors);  
}

function ds_sanitize_loja(&$fields_loja) {
  $fields_loja['user_login']   =  isset($fields_loja['user_login'])  ? sanitize_user($fields_loja['user_login']) : '';
  $fields_loja['user_pass']    =  isset($fields_loja['user_pass'])   ? esc_attr($fields_loja['user_pass']) : '';
  $fields_loja['user_email']   =  isset($fields_loja['user_email'])  ? sanitize_email($fields_loja['user_email']) : '';
  $fields_loja['user_url']     =  isset($fields_loja['user_url'])    ? esc_url($fields_loja['user_url']) : '';
  $fields_loja['first_name']   =  isset($fields_loja['first_name'])  ? sanitize_text_field($fields_loja['first_name']) : '';
  $fields_loja['last_name']    =  isset($fields_loja['last_name'])   ? sanitize_text_field($fields_loja['last_name']) : '';
  $fields_loja['nickname']     =  isset($fields_loja['nickname'])    ? sanitize_text_field($fields_loja['nickname']) : '';
  $fields_loja['teste']     =  isset($fields_loja['teste'])    ? sanitize_text_field($fields_loja['teste']) : '';
  $fields_loja['description']  =  isset($fields_loja['description']) ? esc_textarea($fields_loja['description']) : '';
}

function ds_display_form_loja($fields_loja = array(), $errors = null) {

  // Check for wp error obj and see if it has any errors  
  if (is_wp_error($errors) && count($errors->get_error_messages()) > 0) {

// Display errors
?><ul><?php
foreach ($errors->get_error_messages() as $key => $val) {
  ?><li>
    <?php echo $val; ?>
  </li><?php
}
?></ul><?php
  }

  // Display form

  ?><form action="<?php $_SERVER['REQUEST_URI'] ?>" method="post">
<div>
  <label for="user_login">Username <strong>*</strong></label>
  <input type="text" name="user_login" value="<?php echo (isset($fields_loja['user_login']) ? $fields_loja['user_login'] : '') ?>">
</div>

<div>
  <label for="user_pass">Password <strong>*</strong></label>
  <input type="password" name="user_pass">
</div>

<div>
  <label for="email">Email <strong>*</strong></label>
  <input type="text" name="user_email" value="<?php echo (isset($fields_loja['user_email']) ? $fields_loja['user_email'] : '') ?>">
</div>

<div>
  <label for="website">Website</label>
  <input type="text" name="user_url" value="<?php echo (isset($fields_loja['user_url']) ? $fields_loja['user_url'] : '') ?>">
</div>

<div>
  <label for="firstname">First Name</label>
  <input type="text" name="first_name" value="<?php echo (isset($fields_loja['first_name']) ? $fields_loja['first_name'] : '') ?>">
</div>

<div>
  <label for="website">Last Name</label>
  <input type="text" name="last_name" value="<?php echo (isset($fields_loja['last_name']) ? $fields_loja['last_name'] : '') ?>">
</div>

<div>
  <label for="nickname">Nickname</label>
  <input type="text" name="nickname" value="<?php echo (isset($fields_loja['nickname']) ? $fields_loja['nickname'] : '') ?>">
</div>

<div>
  <label for="nickname">Teste</label>
  <input type="text" name="teste" value="<?php echo (isset($fields_loja['teste']) ? $fields_loja['teste'] : '') ?>">
</div>

<div>
  <label for="bio">About / Bio</label>
  <textarea name="description"><?php echo (isset($fields_loja['description']) ? $fields_loja['description'] : '') ?></textarea>
</div>

<input type="submit" name="submit_loja" value="Register">
</form><?php
}

function ds_get_fields_loja() {
  return array(
    'user_login'   =>  isset($_POST['user_login'])   ?  $_POST['user_login']   :  '',
    'user_pass'    =>  isset($_POST['user_pass'])    ?  $_POST['user_pass']    :  '',
    'user_email'   =>  isset($_POST['user_email'])   ?  $_POST['user_email']        :  '',
    'user_url'     =>  isset($_POST['user_url'])     ?  $_POST['user_url']     :  '',
    'first_name'   =>  isset($_POST['first_name'])   ?  $_POST['first_name']        :  '',
    'last_name'    =>  isset($_POST['last_name'])    ?  $_POST['last_name']        :  '',
    'nickname'     =>  isset($_POST['nickname'])     ?  $_POST['nickname']     :  '',
    'description'  =>  isset($_POST['description'])  ?  $_POST['description']  :  '',
    'teste'  =>  isset($_POST['teste'])  ?  $_POST['teste']  :  '',
  );
}

function ds_validate_loja(&$fields_loja, &$errors) {

  // Make sure there is a proper wp error obj
  // If not, make one
  if (!is_wp_error($errors))  $errors = new WP_Error;

  // Validate form data

  if (empty($fields_loja['user_login']) || empty($fields_loja['user_pass']) || empty($fields_loja['user_email'])) {
    $errors->add('field', 'Required form field is missing');
  }

  if (strlen($fields_loja['user_login']) < 4) {
    $errors->add('username_length', 'Username too short. At least 4 characters is required');
  }

  if (username_exists($fields_loja['user_login']))
    $errors->add('user_name', 'Sorry, that username already exists!');

  if (!validate_username($fields_loja['user_login'])) {
    $errors->add('username_invalid', 'Sorry, the username you entered is not valid');
  }

  if (strlen($fields_loja['user_pass']) < 5) {
    $errors->add('user_pass', 'Password length must be greater than 5');
  }

  if (!is_email($fields_loja['user_email'])) {
    $errors->add('email_invalid', 'Email is not valid');
  }

  if (email_exists($fields_loja['user_email'])) {
    $errors->add('email', 'Email Already in use');
  }

  if (!empty($fields_loja['user_url'])) {
    if (!filter_var($fields_loja['user_url'], FILTER_VALIDATE_URL)) {
      $errors->add('user_url', 'Website is not a valid URL');
    }
  }

  // If errors were produced, fail
  if (count($errors->get_error_messages()) > 0) {
    return false;
  }

  // Else, success!
  return true;
}

After using @cybmeta code, there was one problem left: the submit button had "name='submit_user'", instead of "name='submit_loja'". Just a dumb error.

Thnx to @cybmeta for helping with the correct info to add the role.

1

You can pass the user's role directly to wp_insert_user(). First, you can try to add your custom role to the WP_Roles object, then pass the custom role to the user properties:

// Add custom roles only once to avoid unnecessary database calls.
// It is usually done during plugin activation.
register_activation_hook( __FILE__,  'cyb_add_roles' );
function cyb_create_role() {

    // array with capabilities
    $lojas_caps = array();

    add_role( 'lojas', 'Lojas', $lojas_caps );

}

function ds_registration_form(&$fields_user, &$errors) {

    // ....

    $fields_loja['role'] = 'lojas';
    $loja_id = wp_insert_user( $fields_loja );

    // Or it can be set to default role and then
    // add the custom role as additional role
    // $loja_id = wp_insert_user( $fields_loja );
    // if( ! is_wp_error( $loja_id ) ) {
    //     $user = new WP_User( $loja_id );
    //     $user->add_role( 'lojas' );
    // }


    // ....
}
7
  • Dind't work. The new user still gets registered as 'subscriber' and the new role don't even show up in the roles list inside the admin. – Marcelo Henriques Cortez Sep 21 '17 at 16:10
  • Now, the role is created. But the registered user still gets the 'subscriber' role. – Marcelo Henriques Cortez Sep 21 '17 at 16:29
  • I've updated my answer; note that $loja_id returned by wp_insert_user() is just the user ID, not a WP_User object, and so, you can not use the add_role method directly on $loja_id. – cybmeta Sep 21 '17 at 16:45
  • I tried with that 'if', still don't work. I updated the code. – Marcelo Henriques Cortez Sep 21 '17 at 16:57
  • 1
    I forgot to remove that part of '$loja_id->add_role' from the code I posted, I wasn't using it anymore. I tried a simpler code, and it worked, the new user got the role 'loja'. I'll try to build the rest of the form and the functions and see if I can spot the problem. If I do, I'll post the answer here. – Marcelo Henriques Cortez Sep 22 '17 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.