WordPress Internal @ Mentions

This is a little tricky because sanitize_user allows spaces in usernames, meaning it difficult to avoid grabbing the whole phrase ‘@johndoe said that … ‘ as opposed to just the actual username ‘@johndoe’ and you have no separator at the end that would help. To avoid that I imposed a requirement that spaces in the username be replaced with ‘+’.

function look_for_author($login) {
  if (!empty($login[1])) {
    $lname = str_replace('+',' ',$login[1]);
    $user = get_user_by('login',$lname);
    if (!empty($user)) return ' <a href="'.get_author_posts_url($user->ID).'">'.$lname.'</a> ';
  }
  return ' '.$login[0].' ';
}

function hyperlink_authors( $content ){
  $content = preg_replace_callback(
    '/[\s>]+@([A-Za-z0-9_.\-*@\+]+)[^A-Za-z0-9_.\-*@\+]/',
    'look_for_author',
    $content
  );
  return $content;
}
add_filter( 'the_content', 'hyperlink_authors', 1 );

I would not expect this solution to be very robust, not without a lot of tweaking of the regex. And I think you would be better off with a shortcode, but there you go.

Note: It occurred to me that this site has a similar mention-like functionality. When writing a comment, you can notify other users by writing “@username” but usernames here can have spaces as with WordPress. The “spaces” problem here was solved by requiring that spaces just be removed, rather than substituted with “+” signs. That could be another way to solve approach the problem.

Leave a Comment