这有点棘手,因为sanitize_user
允许在用户名中使用空格,这意味着很难避免抓住整个短语“@johndoe said that…”与实际用户名“@johndoe”相反,您在末尾没有分隔符,这会有所帮助。为了避免这种情况,我强制要求用户名中的空格替换为“+”。
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 );
我不希望这个解决方案非常健壮,除非对regex进行大量调整。我想你最好是
shortcode, 但你来了。
注意:我突然想到,这个网站有一个类似于提及的功能。写评论时,你可以通过写“@用户名”通知其他用户,但这里的用户名可以像WordPress一样有空格。这里的“空间”问题由requiring that spaces just be removed, 而不是用“+”符号代替。这可能是解决问题的另一种方法。