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>
シンプルな記述
<?php $terms = wp_get_object_terms($post->ID, 'taxonomy', ['parent' => 0]); ?> <?php foreach($terms as $term): ?> <?php echo "$term->name" ?> //親ターム名表示 <?php endforeach; ?>
もっとスマートな方法があるかもしれませんが、これでうまくいきました。
ゼヒトモ内でのプロフィール: ROCKSTREAM, ゼヒトモのホームページ作成・制作サービス, 仕事をお願いしたい依頼者と様々な「プロ」をつなぐサービス
2025/01/31
JQuery
2025/01/01
神社
御朱印
相模原
2024/10/27
ブラウザ
カスタム投稿
Wordpress
2024/08/20
神社
御朱印
2024/07/06
神社
御朱印