WordPress Hide Author page from Unauthenticated users

I wanted to hide author pages from authenticated users on a WordPress site for a couple of reasons:

  • Security – By going to http://wordpresssite.com/?author=1 you can usually get the WordPress admin username (even if its changed) which opens an attack vector
  • Privacy – The user profiles displayed additional user information that would be better kept private

The following code snippit stops the author request from resolving the username, and immediately displays an error.

function hide_author_request($request)
{
    //Disable the redirect
    if (isset($request['author']) && !is_user_logged_in()) {
        unset($request['author']);

        //Immediately display the 404, and exit
        status_header(404);
        nocache_headers();
        include( get_404_template() );
        exit;
    }

    return $request;
}

add_filter('request', 'hide_author_request');