Skip to content

Instantly share code, notes, and snippets.

@KaineLabs
Created November 9, 2018 00:43
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 KaineLabs/be878ed9d490ffd6627c7d30924babcb to your computer and use it in GitHub Desktop.
Save KaineLabs/be878ed9d490ffd6627c7d30924babcb to your computer and use it in GitHub Desktop.
Add User Role to Registeration Form
<?php
/**
* Get User Registeration field
*/
function yzc_add_registation_role_field() {
// Get Allowed Roles.
$allowed_roles = yzc_allowed_registration_roles();
?>
<p class="form-row form-row-first">
<label for="yz_reg_role"><?php _e( 'User Role', 'youzer' ); ?></label>
<select class="input-text" name="role" id="yz_reg_role">
<?php foreach ( $allowed_roles as $role ): ?>
<option <?php if ( ! empty( $_POST['role'] ) && $_POST['role'] == $role['role'] ) esc_attr_e( 'selected' ); ?> value="<?php echo $role['role']; ?>"><?php echo $role['title']; ?></option>
<?php endforeach ?>
</select>
</p>
<?php
}
add_action( 'bp_signup_profile_fields', 'yzc_add_registation_role_field' );
/**
* Allowed Registration Roles.
*/
function yzc_allowed_registration_roles() {
$roles = array(
array( 'role' => 'subscriber', 'title' => __( 'Artist/Band', 'youzer' ) ),
array( 'role' => 'employer', 'title' => __( 'Business', 'youzer' ) ),
array( 'role' => 'sales', 'title' => __( 'Affiliates', 'youzer' ) ),
array( 'role' => 'customer', 'title' => __( 'Fan', 'youzer' ) ),
);
return apply_filters( 'yzc_allowed_registration_roles', $roles );
}
/**
* Save Registeration User Role.
*/
function yzc_save_user_role( $user_id ) {
if ( ! isset( $_POST['role'] ) || empty( $_POST['role'] ) ) {
return;
}
// Get Allowed Roles.
$roles = yzc_allowed_registration_roles();
$allowed_roles = wp_list_pluck( $roles, 'role' );
if ( ! in_array( $_POST['role'], $allowed_roles ) ) {
return;
}
add_user_meta( $user_id, 'yzc_role', $_POST['role'] );
}
add_action( 'bp_core_signup_user', 'yzc_save_user_role' );
/**
* Update User Role On Activation.
*/
function yzc_update_user_role_on_activation( $user_id ) {
// Get Role.
$role = get_user_meta( $user_id, 'yzc_role', true );
if ( empty( $role ) ) {
return;
}
// Set Role.
$role = wp_update_user( array( 'ID' => $user_id, 'role' => $role ) );
}
add_action( 'bp_core_activated_user', 'yzc_update_user_role_on_activation', 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment