不少朋友都在询问,如果将WordPress作者存档链接中的用户名改为用户ID,好吧,一起来看看 前端博客 的方法吧。
什么是作者存档页链接
wordpress的里的所有注册用户都有一个专属的链接,称之为作者存档页链接,通常是这样的:
- //未url重写
- http://qianduanblog.com/?author=1
- //已url重写
- http://qianduanblog.com/author/admin
其中未url重写的参数值是用户id,而url重写后的参数值是用户名。通常,我们都使用了url重写,而作者存档页链接暴露了用户名,可能对wordpress的安全性有点点倾斜(而作者的想法是作者的的参数值统一为用户id,如:author/123,用户页面链接的参数值统一为用户id,如:user/123,关于用户页面链接比作者存档页链接要复杂,后续文章再说),所以我们需要修改参数值为用户id。
修改作者存档页链接
首先要做的是,修改存档页链接,如下示例:
- //修改之前
- http://qianduanblog.com/author/admin
- //修改之后
- http://qianduanblog.com/author/123
在wordpress里内置了关于作者存档页链接的钩子,原始的作者存档页链接是这样获取的:
- /**
- *RetrievetheURLtotheauthorpagefortheuserwiththeIDprovided.
- *
- *@since2.1.0
- *@uses$wp_rewriteWP_Rewrite
- *@returnstringTheURLtotheauthor’spage.
- */
- functionget_author_posts_url($author_id,$author_nicename=”){
- global$wp_rewrite;
- $auth_ID=(int)$author_id;
- $link=$wp_rewrite->get_author_permastruct();
- if(emptyempty($link)){
- $file=home_url(‘/’);
- $link=$file.‘?author=’.$auth_ID;
- }else{
- if(”==$author_nicename){
- $user=get_userdata($author_id);
- if(!emptyempty($user->user_nicename))
- $author_nicename=$user–>user_nicename;
- }
- $link=str_replace(‘%author%’,$author_nicename,$link);
- $link=home_url(user_trailingslashit($link));
- }
- $link=apply_filters(‘author_link’,$link,$author_id,$author_nicename);
- return$link;
- }
参考源文档,生成了这样的用户id的作者存档页链接:
- /**
- *修改url重写后的作者存档页的链接变量
- *@sinceyundanran-3beta2
- *2013年10月8日23:23:49
- */
- add_filter(‘author_link’,‘yundanran_author_link’,10,2);
- functionyundanran_author_link($link,$author_id){
- global$wp_rewrite;
- $author_id=(int)$author_id;
- $link=$wp_rewrite->get_author_permastruct();
- if(emptyempty($link)){
- $file=home_url(‘/’);
- $link=$file.‘?author=’.$author_id;
- }else{
- $link=str_replace(‘%author%’,$author_id,$link);
- $link=home_url(user_trailingslashit($link));
- }
- return$link;
- }
修改之后,在前台输出作者存档页的链接:
- get_author_posts_url(1);
- //=>http://qianduanblog.com/author/1
说明钩子使用的是正确的,但当我们打开这个链接的时候,出现了404。这是因为,原始的作者存档页链接的url重写规则是根据用户名来的,而现在修改为了用户id,重写规则不匹配,出现了404。
修改作者存档页查询变量
为了避免出现404,我们需要修改作者存档页的url重写规则。
- /**
- *替换作者的存档页的用户名,防止被其他用途
- *作者存档页链接有2个查询变量,
- *一个是author(作者用户id),用于未url重写
- *另一个是author_name(作者用户名),用于url重写
- *此处做的是,在url重写之后,把author_name替换为author
- *@version1.0
- *@sinceyundanran-3beta2
- *2013年10月8日23:19:13
- *@linkhttps://www.xhsay.com/use-nickname-for-author-slug.html
- */
- add_filter(‘request’,‘yundanran_author_link_request’);
- functionyundanran_author_link_request($query_vars){
- if(array_key_exists(‘author_name’,$query_vars)){
- global$wpdb;
- $author_id=$query_vars[‘author_name’];
- if($author_id){
- $query_vars[‘author’]=$author_id;
- unset($query_vars[‘author_name’]);
- }
- }
- return$query_vars;
- }
很巧合的是,作者存档页的查询变量有2个,之前说过,1个是url未重写的用户id(author
),另一个是url已重写的用户名(author_name
),而现在直接传递过来了用户id,只需要把参数名称author_name
修改为author
即可。
再次打开刚才的链接(http://qianduanblog.com/author/1),出现了正确页面。而如果打开原始的链接(http://qianduanblog.com/author/admin)就会出现404页面了,说明我们的修改正确了。