get_terms()


WordPress関数get_terms()は、分類法(カテゴリー、タグ、カスタムタクソノミー)の用語を取得するために使用されます。

構文

get_terms( array|string $args = array(), string $output = 'names', string $filter = 'raw' );

引数の説明:

  • $args (array|string) — 取得する用語をフィルタリングするためのパラメーター。例: ‘taxonomy’、’hide_empty’ など。
  • $output (string) — 出力形式を指定します。例: ‘names’、’ids’。
  • $filter (string) — データをフィルタリングする方法を指定します。

例 1: カテゴリー一覧を取得する

<?php
$categories = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => false ) );
foreach ( $categories as $category ) {
    echo $category->name;
}
?>

例 2: タグのスラッグを取得する

<?php
$tags = get_terms( array( 'taxonomy' => 'post_tag', 'fields' => 'slugs' ) );
foreach ( $tags as $slug ) {
    echo $slug;
}
?>

例 3: 空の用語を除外して取得する

<?php
$terms = get_terms( array( 'taxonomy' => 'category', 'hide_empty' => true ) );
foreach ( $terms as $term ) {
    echo $term->name;
}
?>

例 4: 特定のタクソノミーのIDを取得する

<?php
$term_ids = get_terms( array( 'taxonomy' => 'custom_taxonomy', 'fields' => 'ids' ) );
foreach ( $term_ids as $id ) {
    echo $id;
}
?>

例 5: 配列を使用してカスタム条件で用語を取得する

<?php
$custom_terms = get_terms( array(
    'taxonomy' => 'custom_taxonomy',
    'orderby' => 'name',
    'order' => 'ASC',
    'number' => 5
) );
foreach ( $custom_terms as $term ) {
    echo $term->name;
}
?>

注意点

  • 多くの用語を取得する場合、パフォーマンスに影響を与える可能性があります。
  • hide_empty引数を設定することで、不要な空の用語を除外できます。
  • カスタムタクソノミーを使用する場合、正しいタクソノミースラッグを指定してください。

関連機能: