LoginSignup
3
3

More than 5 years have passed since last update.

[WordPress] タグアーカイブのパーマリンクをタグIDにする

Last updated at Posted at 2018-01-10

やりたいこと

タグのスラッグ使わないで http://example.com/tag/{$term_ID}/ の形にする。
デフォルトだと意識してタグのスラッグを編集しない限りタグの名前が自動でスラッグになるので、2バイトだと /tag/%E3%82%AB%E3%82%B9%E3%82%BF%E3%83%A0%E3%83%95%E3%82%A3%E3%83%BC%E3%83%AB%E3%83%89/ となってちょっと、、、という場合に。
投稿タグのフィードやページ送りもバッチリOK。

なお、カテゴリーアーカイブのパーマリンクをカテゴリーIDにしたい場合は以下の記事参照。

ソースコード

はいどーん。

<?php
function numeric_term_link( $url, $term, $taxonomy ) {
    global $wp_rewrite;

    // post_tag only
    if ( $taxonomy == 'post_tag' ) {
        if ( $wp_rewrite->using_permalinks() ) {
            $permastruct = $wp_rewrite->get_extra_permastruct( 'post_tag' );
            $permastruct = str_replace( '%post_tag%', $term->term_id, $permastruct );
            $url = home_url( user_trailingslashit( $permastruct, 'tag' ) );
        }
    }
    return $url;
}
add_filter( 'term_link', 'numeric_term_link', 10, 3 );

function add_tag_id_to_qvar( $vars ) {
    $vars[] = 'tag_id';
    return $vars;
}
add_filter( 'query_vars', 'add_tag_id_to_qvar' );

function numeric_tag_rewrite_rules( $rules ) {
    $custom_rules = array();
    foreach ( $rules as $regex => $rewrite ) {
        $regex = str_replace( '/(.+?)/', '/([0-9]{1,})/', $regex );
        $rewrite = str_replace( '?tag=', '?tag_id=', $rewrite );
        $custom_rules[$regex] = $rewrite;
    }
    return $custom_rules;
}
add_filter( 'post_tag_rewrite_rules', 'numeric_tag_rewrite_rules' );
  1. term_link のフィルターフックで numeric_term_link() を実行し、投稿タグアーカイブへのリンクをスラッグらタグIDになるよう変更。なおこれはURLのみを変更するのでこれだけでは片手落ち。
  2. リライトルールでタグIDを使えるように query_vars のフィルターフックで tag_idを追加しておく。
  3. リライトルールにフックは色々あるけど、post_tag_rewrite_rules で投稿タグのリライトルールに限定して改変。
  4. 最後に管理画面の「パーマリンク設定」を変更せずに更新すること

現場からは以上です。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3