Wordpress Author Permalinks
I know how to change the base of the author permalinks, however on my site, I refer to users not by their username but by a number based on their User ID, so User number 5 wrote this post, rather than JohnDoe123 wrote this post.
The problem comes when I go to that users archives and instead of seeing something like example.com/authors/5/ I see example.com/authors/johndoe123/开发者_运维百科 .
How do I change permalinks so that I can pull up author archives using the following structure? :
[wordpress_site_url]/authors/[user_ID]/
This can be done by adding new rewrite rules for each user in exactly the same way you would when changing or removing the author base. So, adapting code from a previous answer, you would add your rewrite rules something like this:
add_filter('author_rewrite_rules', 'my_author_url_with_id_rewrite_rules');
function my_author_url_with_id_rewrite_rules($author_rewrite) {
global $wpdb;
$author_rewrite = array();
$authors = $wpdb->get_results("SELECT ID, user_nicename AS nicename from {$wpdb->users}");
foreach ($authors as $author) {
$author_rewrite["authors/{$author->ID}/page/?([0-9]+)/?$"] = 'index.php?author_name=' . $author->nicename . '&paged=$matches[1]';
$author_rewrite["authors/{$author->ID}/?$"] = "index.php?author_name={$author->nicename}";
}
return $author_rewrite;
}
And then filter the author link:
add_filter('author_link', 'my_author_url_with_id', 1000, 2);
function my_author_url_with_id($link, $author_id) {
$link_base = trailingslashit(get_option('home'));
$link = "authors/$author_id";
return $link_base . $link;
}
Actually I don't think you need to create rules for each user in this case, the following two rules should suffice:
add_filter('author_rewrite_rules', 'my_author_url_with_id_rewrite_rules');
function my_author_url_with_id_rewrite_rules($author_rewrite) {
$author_rewrite = array();
$author_rewrite["authors/([0-9]+)/page/?([0-9]+)/?$"] = 'index.php?author=$matches[1]&paged=$matches[2]';
$author_rewrite["authors/([0-9]+)/?$"] = 'index.php?author=$matches[1]';
return $author_rewrite;
}
精彩评论