Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm looking for a way to link to author pages within one WordPress install simply by putting the @ symbol in front of a person's username in a post.... just like on twitter.

Example:

If the username is "Bill256" and I write "@Bill256" it will be linked to his author page.

share|improve this question

2 Answers 2

up vote 11 down vote accepted

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.

share|improve this answer

Look at the P2 theme. It does this, calling them "Mentions".

http://themes.svn.wordpress.org/p2/1.4.2/inc/mentions.php

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.