之前分享过 将WordPress作者存档链接中的用户名改为昵称,不少朋友都在询问,如果将WordPress作者存档链接中的用户名改为用户ID,好吧,一起来看看 前端博客 的方法吧。
什么是作者存档页链接
wordpress的里的所有注册用户都有一个专属的链接,称之为作者存档页链接,通常是这样的:
// 未url重写
?author=1
// 已url重写
author/admin
其中未url重写的参数值是用户id,而url重写后的参数值是用户名。通常,我们都使用了url重写,而作者存档页链接暴露了用户名,可能对wordpress的安全性有点点倾斜(而作者的想法是作者的的参数值统一为用户id,如:author/123,用户页面链接的参数值统一为用户id,如:user/123,关于用户页面链接比作者存档页链接要复杂,后续文章再说),所以我们需要修改参数值为用户id。
修改作者存档页链接
首先要做的是,修改存档页链接,如下示例:
// 修改之前
author/admin
// 修改之后
author/123
在wordpress里内置了关于作者存档页链接的钩子,原始的作者存档页链接是这样获取的:
/**
* Retrieve the URL to the author page for the user with the ID provided.
*
* @since 2.1.0
* @uses $wp_rewrite WP_Rewrite
* @return string The URL to the author's page.
*/
function get_author_posts_url($author_id, $author_nicename = '') {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty($link) ) {
$file = home_url( '/' );
$link = $file . '?author=' . $auth_ID;
} else {
if ( '' == $author_nicename ) {
$user = get_userdata($author_id);
if ( !empty($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重写后的作者存档页的链接变量
* @since yundanran-3 beta 2
* 2013年10月8日23:23:49
*/
add_filter( 'author_link', 'yundanran_author_link', 10, 2 );
function yundanran_author_link( $link, $author_id) {
global $wp_rewrite;
$author_id = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty($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;
修改之后,在前台输出作者存档页的链接:
1 2

