Filter and validate user role in registration

Question

I want to show a select box for user roles in the registration form. I am using this model:

/* ROLES IN LIST REGISTRATION */
// 1. Add a new form element...

add_action( 'register_form', 'odin_register_form' );
function odin_register_form() {

    global $wp_roles;
    echo '<select name="role" class="input">';
    echo '<option disabled selected value> -- </option>';
    foreach ( $wp_roles->roles as $key=>$value ):
      echo '<option value="'.$key.'">'.$value['name'].'</option>';
    endforeach;
    echo '</select>';
}

// 2. Add validation.

add_filter( 'registration_errors', 'odin_registration_errors', 10, 3 );
function odin_registration_errors( $errors, $sanitized_user_login, $user_email ) {
if (
    empty( $_POST['role'] ) || ! empty( $_POST['role'] ) && trim( $_POST['role'] ) == ''
    || $_POST['role'] == 'administrator'
    || $_POST['role'] == 'editor'
    || $_POST['role'] == 'contributor'
    || $_POST['role'] == 'author'
    || $_POST['role'] == 'shop_manager'
    ) {
     $errors->add( 'role_error', __( '<strong>ERROR</strong>: Select a valid option.', 'odin' ) );
}
return $errors;
}

//3. Finally, save our extra registration user meta.
add_action( 'user_register', 'odin_user_register' );
function odin_user_register( $user_id ) {

if (
    $_POST['role'] != 'administrator'  ||
    $_POST['role'] != 'editor'  ||
    $_POST['role'] != 'contributor'  ||
    $_POST['role'] != 'shop_manager'  ||
    $_POST['role'] != 'author'
) {
    $user_id = wp_update_user( array( 'ID' => $user_id, 'role' => $_POST['role'] ) );
    }
}

The point is that I have not seen the error happen when validation choose an empty option.

So what I alncançar is as follows:

1) Filter the types of users except the Administrator, Editor, Author, Contributor, and the Store Manager. I could just set the Subscriber and Customer functions, but the project must be free to create other roles without having to write the code again.

2) I need to validate the record of the options in this field, because it already has achieved filter rendering of roles in the selection list, we have to ensure that there is the possibility of u stranger inject an option in html with the value ‘administrator’ for example. This may not happen for any of the papers with some editing capability.

I need the hint of you how I can do this.

0
, , , , Adson Cicilioti 3 years 2020-04-01T20:51:20-05:00 0 Answers 72 views 0

Leave an answer

Browse
Browse