大部分wordpress博主一定知道wordpress伪静态后默认的作者专栏链接是“/author/作者名”形式的,如果是单人博客那么倒也没什么,如果是多人博客那么这个默认的地址就有点不个性了,但是wordpress的后台中并没有提供作者栏的伪静态设置选项,那么就来教大家如何修改默认的wordpress作者专栏链接形式。
//更改作者存档前缀
add_action('init', 'change_author_base');
function change_author_base() {
global $wp_rewrite;
$author_slug = 'profile'; // change slug name
$wp_rewrite->author_base = $author_slug;
}
将以上代码加到当前主题的functions.php文件,即可。(修改后作者专栏链接将变成“/别名/作者名”这种形式。)
以上的代码实现了将author 更改为 profile 了,如果你想改成其他的,可以在profile处随意更改。
接着是去掉这个author的方法:
同样在当前主题的functions.php文件内添加如下代码进行实现:
//通过 author_rewrite_rules 钩子添加新的重写规则
add_filter('author_rewrite_rules', 'no_author_base_rewrite_rules');
function no_author_base_rewrite_rules($author_rewrite) {
global $wpdb;
$author_rewrite = array();
$authors = $wpdb->get_results("SELECT user_nicename AS nicename from $wpdb->users");
foreach($authors as $author) {
$author_rewrite["({$author->nicename})/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$"] = 'index.php?author_name=$matches[1]&feed=$matches[2]';
$author_rewrite["({$author->nicename})/page/?([0-9]+)/?$"] = 'index.php?author_name=$matches[1]&paged=$matches[2]';
$author_rewrite["({$author->nicename})/?$"] = 'index.php?author_name=$matches[1]';
}
return $author_rewrite;
}
// 通过 author_link 钩子移除前缀 author
add_filter('author_link', 'no_author_base', 1000, 2);
function no_author_base($link, $author_id) {
$link_base = trailingslashit(get_option('home'));
$link = preg_replace("|^{$link_base}author/|", '', $link);
return $link_base . $link;
}
注:如果添加代码后,访问新的存档地址出现 404 错误,请访问WP后台 >设置>固定链接,重新保存一次即可。