删除WordPress网站文章作者URL中author前缀方法

无评论

作者照片

By 霜天

一般情况下,author这个目录结构是有存在必要的,可以避免与其它页面重名而导致链接混乱。但有些用户可能出于某种需要想直接删除author这个目录结构。今天分享一下删除WordPress网站文章作者URL中author前缀方法,以下是具体实现方法:

/*

删除文章作者URL中的author目录

代码来源: www.wpzhinan.com

*/

// 通过 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;

}

代码说明:请将以上代码插入主题fuction.php即可。以上代码的原理是在删除author目录的同时需通过hooks添加一个新的作者页重写规则以变更旧URL结构为新的,否则如果直接删除了事的话就会出现404错误页面。注意:添加代码后,必须要到固定链接页面再次保存并更新链接结构以更新.htaccess文件,使新的链接结构生效,从而避免出现404页面。

发表评论