get_term_meta()


WordPress関数get_term_meta()は、特定のタクソノミータームに関連付けられたメタデータを取得するために使用されます。

構文

get_term_meta( int $term_id, string $meta_key = '', bool $single = false );

引数の説明

  • $term_id (int) — メタデータを取得するタームのID。
  • $meta_key (string) — 取得するメタデータのキー。省略した場合、すべてのメタデータが返されます。
  • $single (bool)trueの場合、単一の値を返します。falseの場合、配列を返します。

例1: 特定のタームメタデータの取得

指定されたタームIDの特定のメタデータを取得します。

<?php $value = get_term_meta( get_term_by( 'slug', 'category-slug', 'category' )->term_id, 'meta_key', true ); ?>

例2: 全メタデータを取得

特定のタームに関連付けられたすべてのメタデータを取得します。

<?php $all_meta = get_term_meta( get_term_by( 'slug', 'tag-slug', 'post_tag' )->term_id ); ?>

例3: メタデータの存在確認

タームメタデータが存在するかどうかを確認します。

<?php if ( get_term_meta( get_term_by( 'slug', 'category-slug', 'category' )->term_id, 'meta_key', true ) ) { echo 'Meta exists'; } ?>

例4: カスタム値の表示

タームメタデータのカスタム値を表示します。

<?php echo get_term_meta( get_term_by( 'slug', 'custom-taxonomy-slug', 'custom_taxonomy' )->term_id, 'custom_meta_key', true ); ?>

例5: メタデータを条件付きで使用

タームメタデータが特定の値の場合に特定の処理を行います。

<?php
if ( get_term_meta( get_term_by( 'slug', 'category-slug', 'category' )->term_id, 'meta_key', true ) === 'specific_value' ) {
    echo 'This is the specific value.';
}
?>

注意事項

  • タームメタデータは、WordPressのカスタムタクソノミーやカテゴリに付随する追加データを効率的に管理するのに役立ちます。
  • メタデータが存在しない場合、get_term_meta()は空文字列や空の配列を返しますので、その扱いに注意してください。

関連機能: