概要
get_the_terms
関数は、特定の投稿に関連付けられているタクソノミー(カテゴリーやタグなど)情報を取得するために使用されます。この関数は、投稿記事のタクソノミー情報を取得する際に非常に便利で、例えば、以下のような機能を実装する際によく使われます。
- 投稿に関連するカテゴリーを表示
- タグリストを生成
- カスタムタクソノミーの情報取得
- 投稿のメタデータとしてタクソノミーを表示
- タクソノミーによるフィルタリング機能の実装
- 投稿詳細ページでのナビゲーション作成
- タクソノミーに基づくランキングページの作成
- SEO向けの構造化データ生成
構文
get_the_terms( int $post_id, string $taxonomy );
パラメータ
$post_id
(int): タクソノミー情報を取得したい投稿のID。$taxonomy
(string): 取得するタクソノミーのスラッグ(例: ‘category’, ‘post_tag’)。
戻り値
- 成功した場合、タクソノミー情報の配列を返します。失敗した場合は
false
を返します。
関連する関数
使用可能なバージョン
get_the_terms
関数は、WordPress 3.0から使用可能です。
コアファイルのパス
- wp-includes/taxonomy.php
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |
サンプルコード
サンプルコード1: 投稿のカテゴリーを取得
このコードは、特定の投稿IDに関連するカテゴリーを取得し、表示するサンプルです。
$post_id = 1; // 投稿IDを指定
$terms = get_the_terms($post_id, 'category'); // カテゴリーを取得
if ($terms && !is_wp_error($terms)) {
foreach ($terms as $term) {
echo $term->name . '<br>';
}
}
引用元: https://developer.wordpress.org/reference/functions/get_the_terms/
サンプルコード2: 複数のタクソノミーを取得
この例では、特定の投稿から複数のタクソノミーを取得して、それをループで表示します。
$post_id = 2; // 投稿IDを指定
$categories = get_the_terms($post_id, 'category'); // カテゴリーを取得
$tags = get_the_terms($post_id, 'post_tag'); // タグを取得
if ($categories && !is_wp_error($categories)) {
foreach ($categories as $category) {
echo $category->name . ' (Category)<br>';
}
}
if ($tags && !is_wp_error($tags)) {
foreach ($tags as $tag) {
echo $tag->name . ' (Tag)<br>';
}
}
引用元: https://developer.wordpress.org/reference/functions/get_the_terms/
サンプルコード3: カスタムタクソノミーを取得
このコードは、カスタムタクソノミーからタームを取得し表示します。
$post_id = 3; // 投稿ID
$custom_terms = get_the_terms($post_id, 'custom_taxonomy'); // カスタムタクソノミーを取得
if ($custom_terms && !is_wp_error($custom_terms)) {
foreach ($custom_terms as $term) {
echo $term->name . '<br>';
}
}
引用元: https://developer.wordpress.org/reference/functions/get_the_terms/
サンプルコード4: タクソノミー情報がない場合の処理
このコードでは、タクソノミーが取得できなかった場合のエラーハンドリングを示します。
$post_id = 4; // 投稿ID
$terms = get_the_terms($post_id, 'category');
if ($terms === false) {
echo 'タクソノミーが見つかりません。';
} elseif (is_wp_error($terms)) {
echo 'エラーが発生しました。';
} else {
foreach ($terms as $term) {
echo $term->name . '<br>';
}
}
引用元: https://developer.wordpress.org/reference/functions/get_the_terms/
サンプルコード5: タームのリンクを表示
このコードは、タームのリンクを作成し表示します。
$post_id = 5; // 投稿IDを指定
$terms = get_the_terms($post_id, 'category');
if ($terms && !is_wp_error($terms)) {
foreach ($terms as $term) {
$term_link = get_term_link($term); // タームのリンクを取得
echo '<a href="' . esc_url($term_link) . '">' . esc_html($term->name) . '</a><br>';
}
}
引用元: https://developer.wordpress.org/reference/functions/get_the_terms/