Wordpress作者永久链接

时间:2011-02-18 11:41:12

标签: wordpress permalinks

我知道如何更改作者永久链接的基础,但是在我的网站上,我指的是用户不是通过用户名而是通过基于用户ID的数字,所以用户编号5写了这篇文章,而不是JohnDoe123写的这篇文章。

当我转到那些用户档案而不是看到像example.com/authors/5/这样的内容时,问题出现了。我看到example.com/authors/johndoe123/。

如何更改永久链接以便我可以使用以下结构提取作者档案? :

[wordpress_site_url] /作者/ [USER_ID] /

1 个答案:

答案 0 :(得分:5)

这可以通过为每个用户添加新的重写规则来完成,其方式与更改或删除作者库时完全相同。因此,调整previous answer中的代码,您可以添加如下所示的重写规则:

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;
}

然后过滤作者链接:

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;
}

实际上我认为在这种情况下你不需要为每个用户创建规则,以下两个规则就足够了:

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;
}
相关问题