Using the below code to chnage the author page url to use the “nickname”. Works ok but when the nickname is more than one word it doesnt make it url friendly. Any way to do this?
add_filter( 'request', 'wpse5742_request' );
function wpse5742_request( $query_vars ) {
if ( array_key_exists( 'author_name', $query_vars ) ) {
global $wpdb;
$author_id = $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key='nickname' AND meta_value = %s", $query_vars['author_name'] ) );
if ( $author_id ) {
$query_vars['author'] = $author_id;
unset( $query_vars['author_name'] );
}
}
return $query_vars;
}
add_filter( 'author_link', 'wpse5742_author_link', 10, 3 );
function wpse5742_author_link( $link, $author_id, $author_nicename ) {
$author_nickname = get_user_meta( $author_id, 'nickname', true );
if ( $author_nickname ) {
$link = str_replace( $author_nicename, $author_nickname, $link );
}
return $link;
}
add_action( 'user_profile_update_errors', 'wpse5742_set_user_nicename_to_nickname', 10, 3 );
function wpse5742_set_user_nicename_to_nickname( &$errors, $update, &$user ){
if ( ! empty( $user->nickname ) ) {
$user->user_nicename = sanitize_title( $user->nickname, $user->display_name );
}
}
You’ve already used
sanitize_title
once in you code. You need to use that in again, inside thewpse5742_author_link
function.That should take care of the spaces. Another other option is to use
urlencode
butsanitize_title
keeps things consistent.I (minimally) tested your code with that change and it seems to work.