最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

author - author_link filter not work correctly

programmeradmin1浏览0评论

i want to change author link page. by default it's: site/author/user_nice_name

but i want change it to: site/teacher/user_nice_name

i used this code and it worked, but when i click on the user link i get 404 error.

function custom_author_link($link, $author_id, $author_nicename) {
    $author_nicename = get_the_author_meta( 'user_nicename' );
    $link = home_url( user_trailingslashit( 'teacher' ) ) . $author_nicename;
    return $link;

}
add_filter('author_link', 'custom_author_link', 10, 3);

i want to change author link page. by default it's: site/author/user_nice_name

but i want change it to: site/teacher/user_nice_name

i used this code and it worked, but when i click on the user link i get 404 error.

function custom_author_link($link, $author_id, $author_nicename) {
    $author_nicename = get_the_author_meta( 'user_nicename' );
    $link = home_url( user_trailingslashit( 'teacher' ) ) . $author_nicename;
    return $link;

}
add_filter('author_link', 'custom_author_link', 10, 3);
Share Improve this question asked Apr 21, 2020 at 13:52 RezaReza 1
Add a comment  | 

1 Answer 1

Reset to default 1

The problem is that while you can change the URL, you also need to make sure WordPress knows what to do with it. This is called the Rewrite API. There's a filter specifically for author URLs. If we print that, it looks like this:

Array
(
    [author/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$] => index.php?author_name=$matches[1]&feed=$matches[2]
    [author/([^/]+)/(feed|rdf|rss|rss2|atom)/?$] => index.php?author_name=$matches[1]&feed=$matches[2]
    [author/([^/]+)/embed/?$] => index.php?author_name=$matches[1]&embed=true
    [author/([^/]+)/page/?([0-9]{1,})/?$] => index.php?author_name=$matches[1]&paged=$matches[2]
    [author/([^/]+)/?$] => index.php?author_name=$matches[1]
)

The array key is the regex pattern for the URL. The array value is the template that WordPress loads. So say somebody goes to someurl/author/bob. That matches the last item in the array, author/([^/]+)/?$, and WordPress loads index.php?author_name=$matches[1] as a result, resolving it to an individual author's page.

So, in order to update the user's URLs, here's what you'd do:

add_filter( 'author_rewrite_rules', function($author_rewrites) {

    $teacher_rewrites = array();
    foreach ( $author_rewrites as $pattern => $template ) {
        $teacher_rewrites[ str_replace('author', 'teacher', $pattern ) ] = $template;
    }

    return $teacher_rewrites;
} );

Last but not least, you'd need to visit the Permalinks page in the admin to trigger a refresh of the rewrite rules. WordPress doesn't fire the rewrite filters on every page load for efficiency's sake, only in specific situations.

发布评论

评论列表(0)

  1. 暂无评论