この記事は2017年1月30日に書かれたもので、内容が古い可能性がありますのでご注意ください。
WordPressでテンプレート内でカテゴリ名を出し分けたい時ってありますよね?
通常のカテゴリ取得方法
$category = get_the_category(); $cat_name = $category[0]->cat_name; <?php echo $cat_name; ?>
カテゴリーが第1階層までなら通常の記述でOKなのですが、
親子それぞれにカテゴリー登録がされていて、上記の記述をしても親⇒子の順に取得してくれるとは限らないのです。
(カテゴリーによって親子バラバラの表示になってしまう)
最下層のカテゴリ取得方法
functions.phpに追記
function get_term_descendants ( $post_id ='', $tax_name = 'category' ) { $terms = get_the_terms( $post_id, $tax_name ); if ( empty( $terms )) return false; $candidate = $terms; $count = count( $terms ); if ( $count > 1 ): foreach( $terms as $key => $term ): foreach( $terms as $term2 ): if ( term_is_ancestor_of( $term->term_id, $term2->term_id, $tax_name ) ) { unset( $candidate[$key] ); break; } endforeach; endforeach; endif; return $candidate; }
表示させたい箇所に追記
<?php $descends = get_term_descendants(); if ( $descends ): foreach ( $descends as $descend ): $term_name = $descend->name; endforeach; endif; ?> <?php echo $term_name; ?>
以上で問題なく表示されるかと思います。
こちらのサイトを参考にし、この原因をfixすることができました。
投稿が所属するカテゴリの先祖や子孫を取得するあれこれ。