Home » Php » php – WordPress: Change author URL to show author ID

php – WordPress: Change author URL to show author ID

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’d like to change the author URL from example.com/authors/<author-nicename> to example.com/authors/<author-id>. So far I tried modifying a code that changes author nicename to nickname in the URL, but this isn’t working. Here’s the code:

function author_url_request ( $query_vars ) {
    if ( array_key_exists( 'author_name', $query_vars ) ) {
        global $wpdb;
        $author_id = $wpdb->get_var( $wpdb->prepare( "SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key='nickname' AND meta_value = %s", $query_vars['author_name'] ) );
        if ( $author_id ) {
            $query_vars['author'] = $author_id;
            unset( $query_vars['author_name'] );    
        }
    }
    return $query_vars;
}
add_filter( 'request', 'author_url_request' );

function change_author_link ( $link, $author_id, $author_nicename ){
    $link = str_replace( $author_nicename, $author_id, $link );
    return $link;
}
add_filter( 'author_link', 'change_author_link', 10, 3 );

function set_author_nicename_to_id ( &$errors, $update, &$user ) {
    $user->user_nicename = $user->ID;
    print_r($errors);
}
add_action( 'user_profile_update_errors', 'set_author_nicename_to_id', 10, 3 );

Any help with this would be really appreciated.

How to&Answers: