Hiding Active Directory user IDs from WordPress author slugs

I recently set up a corporate WordPress blog system. With the Active Directory Integration plugin, users can sign in with their corporate ID and password.

But here’s a problem: each blog post has a link to the author’s profile. That profile’s URL includes the user ID. The corporation’s security standards say we can’t expose user IDs to the world, so the author profile URLs have to be sanitized.

It took a while to figure out a solution, but the end result is reasonable.

I found this post at StackExchange’s WordPress site. Adding the first two code snippets (below) to the end of wp-config.php tells WordPress to use the user’s nickname metadata to construct the profile URLs:

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;
}

But wait, there’s more!

Now you have to get a proper value into the nickname field. Active Directory Integration makes this easy. In this plugin’s settings, go to the User Meta tab and enter this into the Additional User Attributes field:¬†mailnickname:string:nickname. You’ll may need to replace mailnickname with your own Active Directory user attribute if it isn’t appropriate for you.

That’s it. The next time a user logs in, the nickname field is updated, and all future profile URLs for that user will not have a user ID.

Leave a Reply

Your email address will not be published. Required fields are marked *