Skip to content

Instantly share code, notes, and snippets.

@mjangda
Created May 28, 2012 21:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mjangda/2821239 to your computer and use it in GitHub Desktop.
Save mjangda/2821239 to your computer and use it in GitHub Desktop.
Better author URLs for WordPress. This enables author URLs like /author/firstname-lastname/ or /author/display_name/ instead of the usual /author/user_login/ but comes at a performance cost.
<?php
/**
* Handle author request to change query string as username
*
* This enables author URLs like /author/firstname-lastname/ or /author/display_name/ instead of the usual /author/user_login/
*/
function tc_handle_author_request( $query_vars ) {
if ( ! empty( $query_vars['author_name'] ) ) {
$authors = get_users( array( 'who' => 'authors' ) );
foreach ( $authors as $author ) {
$matched = false;
if ( $author->user_firstname && $author->user_lastname ) {
$name = sprintf( '%s %s', $author->user_firstname, $author->user_lastname );
if ( in_array( $query_vars['author_name'], array( sanitize_title_with_dashes( $name ), sanitize_key( $name ) ) ) )
$matched = true;
} elseif ( $author->display_name ) {
if ( in_array( $query_vars['author_name'], array( sanitize_title_with_dashes( $author->display_name ), sanitize_key( $author->display_name ) ) ) )
$matched = true;
}
if ( $matched ) {
$query_vars['author_name'] = $author->user_nicename;
break;
}
}
}
return $query_vars;
}
add_filter( 'request', 'tc_handle_author_request');
<?php
add_filter( 'author_link', 'tc_override_author_posts_url', 10, 3 );
function tc_override_author_posts_url( $url, $author_id, $user_nicename ) {
$author = get_userdata( $author_id );
if ( $author->user_firstname && $author->user_lastname )
$url = sprintf( '%s/author/%s/', home_url(), sanitize_title_with_dashes( sprintf( '%s %s', $author->user_firstname, $author->user_lastname ) ) );
elseif ( $author->display_name )
$url = home_url( '/author/' . sanitize_title_with_dashes( $author->display_name ) . '/' );
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment