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>
もっとスマートな方法があるかもしれませんが、これでうまくいきました。
2023/06/30
神社
御朱印
2023/06/15
Mac
Linux
2023/04/16
時宗
御朱印
2023/04/14
臨済宗
御朱印
2023/04/05
寺院
御朱印