0

I want to change the default WordPress author link (which is /author/user_nicename) to/author/user_id.

And I found it's easy to do that, I achieved this in two ways:

1.I just copy the get_author_posts_url() function from wp-includes/author-template.php and rewrite it in my theme:

function ji_get_user_url($author_id, $author_nicename = '') {
global $wp_rewrite;
$auth_ID = (int) $author_id;
$link = $wp_rewrite->get_author_permastruct();
if ( empty($link) ) {
    $file = home_url( '/' );
    $link = $file . '?author=' . $auth_ID;
}else {
    if ( '' == $author_nicename ) {
        $user = get_userdata($author_id);
        if ( !empty($user->user_nicename) )
            $author_nicename = $author_id;
    }
    $link = str_replace('%author%', $author_id, $link);
    $link = home_url( user_trailingslashit( $link ) );
}
$link = apply_filters( 'author_link', $link, $author_id, $author_nicename );
return $link;
}

2.I used the filter:

function chang_author_link($link,$author_id,$author_nicename){
$user_info = get_userdata(get_current_user_id());
$user_id= $user_info->ID;
$link = str_replace($author_nicename, $user_id, $link);
return $link;
}
add_filter('author_link', 'chang_author_link',10,3);

Either way above can successfully change the default author link to /author/user_id, but that they all returned a 404 not found page!

What happened?

1

The function get_author_posts_url retrieves the url where the posts of a certain author are to be found. If you change the url, that doesn't mean the posts are moved.

In other words, you have moved a sign directing you to Buckingham Palace and expect that by doing so you also have relocated the palace. In effect, as you found out, you end up in the middle of nowhere.

Also beware that since you are modifying the existing filter author_link, the modification will also apply to calls originating in other functions. If you want to apply a filter to a custom made function, it is better to define a custom named filter as well.

  • so I've worked it out myself. – 吉 宁 Jan 18 '17 at 10:19
1

I just solved the puzzle myself.

The truth is ,it's really hard to alter the author link directly by replacing the author slug with an author id.Just like @cjbj said:

you have moved a sign directing you to Buckingham Palace and expect that by doing so you also have relocated the palace.

We need to approach this issue in other ways.

By default wordpress use /user_nicename/as the slug right? So Let's keep the way it is but altering the "content" of user_nicename.In other words,we make the user_id be the user_nicename.

So just do one thing when there is a new user coming in :

wp_update_user(array('user_nicename' => $user_id))

All done!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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