# カスタム分類のパーマリンクを”/カスタム投稿名/カスタム分類名/項目”にする。

- リンク: https://torounit.com/blog/%e3%82%ab%e3%82%b9%e3%82%bf%e3%83%a0%e5%88%86%e9%a1%9e%e3%81%ae%e3%83%91%e3%83%bc%e3%83%9e%e3%83%aa%e3%83%b3%e3%82%af%e3%82%92%e3%82%ab%e3%82%b9%e3%82%bf%e3%83%a0%e6%8a%95%e7%a8%bf%e5%90%8d/
- 公開日: 2011-05-24T11:14:45+09:00
- 作成者: Toro\_Unit

カスタム分類ってデフォルトだと、
 [plain] http://example.com/カスタム分類名/項目[/
plain]

ってなってるんですが、これを
 [plain] http://example.com/カスタム投稿名/カスタム
分類名/項目 [/plain]

にしたい時があると思います。そんな時のハックです。

2011-12-28追記:[Custom Post Type Permalinks](https://torounit.com/plugins/custom-post-type-permalinks/)
にこの機能は実装しています。是非そちらをお使い下さい。

[php]
 add_action( ‘generate_rewrite_rules’, ‘my_rewrite’ ); function my_rewrite(
$wp_rewrite ){ $taxonomies = get_taxonomies(); $taxonomies = array_slice($taxonomies,
4,count($taxonomies)-1); foreach ( $taxonomies as $taxonomy ) :

 $post_types = get_taxonomy($taxonomy)->object_type;

 foreach ($post_types as $post_type){
 $new_rules[$post_type.’/’.$taxonomy.’/(.+?)/?
$’] = ‘index.php?taxonomy=’.$taxonomy.’&term=’.$wp_rewrite->preg_index(1); }

 $wp_rewrite->rules = array_merge($new_rules, $wp_rewrite->rules);

 endforeach;
 }

add_filter( ‘term_link’, ‘my_term_link’ ,10,3);
 function my_term_link( $termlink,
$term, $taxonomy){ $t=get_taxonomy($taxonomy); $wp_home = get_option("home");

 $post_type = $t->object_type[0];
 if(!isset($t->object_type[1])) { $termlink = 
str_replace($wp_home,$wp_home."/".$post_type,$termlink); }

 return $termlink;
 }

[/php]

上記のコードをfunctions.phpに書きこんでください。

デフォルトだと、http://example.com/カスタム投稿名/カスタム分類名/項目でアクセスし
ても、Not Foundになってしまうので、my_rewrite()で、リライトルールを追加します。

そして、下のmy_term_linkの方で、get_term_link等で出力されるURLを書き換えます。

この時、複数の投稿タイプに関連付けられているものは書き換えないようにしています。
タグとかはそういう運用があるかと思います。
 そういう運用をしない場合は [php] if(!
isset($t->object_type[1])) [/php] を外しても大丈夫です。

[php]
 $terms = get_terms(‘カスタム分類’); foreach ($terms as $term) { ?> <li><a
href="<?=get_term_link($term->slug, ‘カスタム分類’);?>"><?=$term->name;?></a></li
> <?php }?>

[/php]

で、カスタム分類の一覧がリンク付きで出ると思いますので、試してみてください。
