Blog

【WordPress】カスタム投稿の親ターム名(カテゴリ)のみを表示する

2015/08/09

カスタム投稿 Wordpress

備忘録です。

先日の【WordPress】カスタム投稿のタクソノミーターム名(カテゴリ)を表示するでは全てのターム(親ターム・子ターム)を取得してしまいます。

親タームのみ取得したい場合の記述方法です。

参考サイト
WordPressで投稿した記事のカスタム分類(タクソノミー)からタームの親を取得する

親ターム名を取得
※taxonomyにタクソノミー名を入力

<?php
$term = array_pop(get_the_terms($post->ID, 'taxonomy'));
$term_p = $term->parent;
if ( ! $term_p == 0 ){
    $term = array_shift(get_the_terms($post->ID, 'taxonomy'));
}
   echo esc_html($term->name);
?>

CSSで装飾したい場合には

<span class="cat_<?php 
$term = array_pop(get_the_terms($post->ID, 'taxonomy'));
        $term_p = $term->parent;
         if ( ! $term_p == 0 ){
           $term = array_shift(get_the_terms($post->ID, 'taxonomy'));
        }
 echo $term->slug; 
?>">
<?php
$term = array_pop(get_the_terms($post->ID, 'taxonomy'));
$term_p = $term->parent;
if ( ! $term_p == 0 ){
    $term = array_shift(get_the_terms($post->ID, 'taxonomy'));
}
   echo esc_html($term->name);
?>
</span>

もっとスマートな方法があるかもしれませんが、これでうまくいきました。

カテゴリー

月間アーカイブ

MORE

ミュージシャンズ・プラザ

神社仏閣ホームーページ制作

ホームページ制作問合せ