0

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

but i want change it to: site.com/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);

1 Answer 1

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.com/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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.