acf_get_taxonomy_terms()


ACFのacf_get_taxonomy_terms()関数は、指定された条件に基づいて分類(taxonomy)の用語(terms)を取得するために使用されます。

構文

acf_get_taxonomy_terms( array $args = array() );

引数の説明:

  • $args (array) — 用語を取得する条件を指定する連想配列。以下は主なキーの説明です。
    • taxonomy (string|array) — 対象とする分類のスラッグ(単数または複数)。
    • hide_empty (bool) — 空の用語を除外するかどうか(デフォルトはtrue)。
    • parent (int) — 特定の親用語に関連付けられた用語のみを取得する。
    • orderby (string) — 結果の並び順(例: 'name', 'count', 'term_id')。
    • order (string) — 並び順の方向('ASC'または'DESC')。

例1: 特定の分類のすべての用語を取得

次のコードは、分類「category」のすべての用語を取得して表示します。

<?php
$terms = acf_get_taxonomy_terms( array( 'taxonomy' => 'category' ) );
print_r( $terms );
?>

例2: 親用語が指定された用語のみを取得

親用語IDが10の用語を取得する場合。

<?php
$terms = acf_get_taxonomy_terms( array( 'taxonomy' => 'category', 'parent' => 10 ) );
foreach ( $terms as $term ) {
    echo $term->name;
}
?>

例3: 並び順を指定して用語を取得

名前で昇順に並べた用語を取得する場合。

<?php
$terms = acf_get_taxonomy_terms( array( 'taxonomy' => 'post_tag', 'orderby' => 'name', 'order' => 'ASC' ) );
?>

例4: 空でない用語を取得

投稿が割り当てられている用語のみを取得する例。

<?php
$terms = acf_get_taxonomy_terms( array( 'taxonomy' => 'category', 'hide_empty' => true ) );
?>

例5: 複数の分類から用語を取得

「category」と「post_tag」の用語を同時に取得する場合。

<?php
$terms = acf_get_taxonomy_terms( array( 'taxonomy' => array( 'category', 'post_tag' ) ) );
?>