WordPress タクソノミーのターム情報を取得して表示する ID/名称/スラッグ

WordPressのget_terms()を使ってタームスラッグからタクソノミーのターム名やID、スラッグなどの情報を取得して表示する方法を解説します。

使い方としては、タームの情報を表示させたいときなどに使用します。

実装コード

  • タクソノミー food
  • ターム ramen
<?php
$terms = get_terms( 'food', array('slug' => 'ramen'));
$term = $terms[0];
echo $term->term_id;    //タームIDを表示
echo $term->slug;    //タームスラッグを表示
echo $term->name;    //ターム名を表示
?>

※現在の記事のターム情報を取得する場合はget_the_termsを使用。以下実装コード

<?php
$terms = get_the_terms($post->ID, 'food');
$term = $terms[0];
$term->term_id;
?>

使用例

ターム所属のタクソノミーIDを表示

<?php
$terms = get_terms( 'food', array('slug' => 'ramen'));
$term = $terms[0];
echo $term->term_taxonomy_id;
?>

ターム所属のタクソノミースラッグを表示

<?php
$terms = get_terms( 'food', array('slug' => 'ramen'));
$term = $terms[0];
echo $term->taxonomy;
?>

タームの説明を表示

<?php
$terms = get_terms( 'food', array('slug' => 'ramen'));
$term = $terms[0];
echo $term->description;
?>

タームの親タームIDを表示

<?php
$terms = get_terms( 'food', array('slug' => 'ramen'));
$term = $terms[0];
echo $term->parent;
?>

タームの記事数を表示

<?php
$terms = get_terms( 'food', array('slug' => 'ramen'));
$term = $terms[0];
echo $term->parent;
?>

補足

現在の記事のターム一覧を表示

<?php
$terms = get_the_terms($post->ID, 'food');
foreach($terms as $term){
    echo $term->name;
    echo $term->slug;
}
?>

get_terms() 使い方

<?php $terms = get_terms( $taxonomies, $args ); ?>
  • 第一引数 タクソノミースラッグを指定。複数可
  • 第二引数 オプションを指定

参考)関数リファレンス/get terms – WordPress Codex 日本語版

Wordpress デザイナーの私的メモ帳

設計編

基本

投稿関連

固定ページ関連

カテゴリー関連

タクソノミー、ターム関連

テンプレート作成

Advance Custom Fieldの使い方

プラグイン

その他

MW WP Form

Contact Form 7

事例

  • このエントリーをはてなブックマークに追加

プロフィール

kura

個人開発歴5年以上。サイト開発・運営。 ペアでエンジニアとアプリ開発しています。

このサイトではWEBデザイン初心者向けになるべく分かりやすいように解説したり、WEBデザインの便利ツール紹介、開発したりしています。

note