Skip to content

Instantly share code, notes, and snippets.

@jorpdesigns
Created July 14, 2021 10:37
Show Gist options
  • Save jorpdesigns/76be91a6325d900705ebe0596c179cb8 to your computer and use it in GitHub Desktop.
Save jorpdesigns/76be91a6325d900705ebe0596c179cb8 to your computer and use it in GitHub Desktop.
Snippet to add nicename field to WordPress user profile
<?php
add_action( 'personal_options', 'user_edit_ob_start' );
add_action( 'show_user_profile', 'insert_nicename_input' );
add_action( 'edit_user_profile', 'insert_nicename_input' );
add_action( 'user_profile_update_errors', 'profile_update', 10, 3 );
function user_edit_ob_start() {
ob_start();
}
function insert_nicename_input( $user ) {
$content = ob_get_clean();
$regex = '/<tr(.*)class="(.*)\buser-user-login-wrap\b(.*)"(.*)>([\s\S]*?)<\/tr>/';
$nicename_row = sprintf(
'<tr class="user-user-nicename-wrap"><th><label for="user_nicename">%1$s</label></th><td><input type="text" name="user_nicename" id="user_nicename" value="%2$s" class="regular-text" />' . "\n" . '<span class="description">%3$s</span></td></tr>',
esc_html__( 'Nicename' ),
esc_attr( $user->user_nicename ),
esc_html__( 'Must be unique.' )
);
echo preg_replace( $regex, '\0' . $nicename_row, $content );
}
function profile_update( $errors, $update, $user ) {
if ( !$update ) return;
if ( empty( $_POST['user_nicename'] ) ) {
$errors->add(
'empty_nicename',
sprintf(
'<strong>%1$s</strong>: %2$s',
esc_html__( 'Error' ),
esc_html__( 'Please enter a Nicename.' )
),
array( 'form-field' => 'user_nicename' )
);
} else {
$user->user_nicename = $_POST['user_nicename'];
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment