WordPress如何删除文章作者URL中author前缀 - 利剑分享-科技生活-利剑分享-科技生活
利剑分享-科技生活-利剑分享-科技生活
利剑分享-科技生活

WordPress如何删除文章作者URL中author前缀

WordPress如何删除文章作者URL中author前缀

上篇教程已教大家如何修改文章作者URL中的author,这篇文章将教您如何删除文章作者URL中的author前缀。本来可以将两篇文章合在一起的,但考虑到为了方便用户查找解决方案,因此特意分开介绍。一般情况下,author这个目录结构是有存在必要的,可以避免与其它页面重名而导致链接混乱。但有些用户可能出于某种需要想直接删除author这个目录结构。本文将教您删除文章作者URL中的author目录,以下是具体实现方法:

/*
删除文章作者URL中的author目录
代码来源: www.wpzxbj.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页面。

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享