WordPress纯代码实现tag中文转换为ID

  

wordpress的tag标签量较小的时候适合seo,但是多了以后,特别是中文同音不同调的tag,使用转换成拼音可能导致新tag自动显示为旧tag文字的错误
文章及tag较多的时候,建议使用tag的id,纯代码实现方法如下,主题的function.php中加入以下代码即可
注意:适合新站,旧站会导致tag的url 404错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
add_action('generate_rewrite_rules','tag_rewrite_rules');
add_filter('term_link','tag_term_link',10,3);
add_action('query_vars', 'tag_query_vars');
function tag_rewrite_rules($wp_rewrite){
    $new_rules = array(
    'tag/(\d+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?tag_id=$matches[1]&feed=$matches[2]',
    'tag/(\d+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?tag_id=$matches[1]&feed=$matches[2]',
    'tag/(\d+)/embed/?$' => 'index.php?tag_id=$matches[1]&embed=true',
    'tag/(\d+)/page/(\d+)/?$' => 'index.php?tag_id=$matches[1]&paged=$matches[2]',
    'tag/(\d+)/?$' => 'index.php?tag_id=$matches[1]',);
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;}
function tag_term_link($link,$term,$taxonomy){
    if($taxonomy=='post_tag'){
        return home_url('/tag/'.$term->term_id);}
return $link;}
function tag_query_vars($public_query_vars){
        $public_query_vars[] = 'tag_id';
return $public_query_vars;}

您必须才能评论!