WordPress タクソノミーのターム取得関数を汎用化する方法

WordPress でカスタムタクソノミーを使う場合、ターム一覧を取得する処理を毎回書くのは面倒ですよね。
そこで、汎用的に使える ターム取得関数 を用意しておくと、どんなプロジェクトでも簡単に再利用できます。

この記事では、以下の2つの関数を例に解説します。

  • taxonomy_terms_list() … 任意のタクソノミーのターム一覧を取得
  • get_sample_terms()sample_taxonomy 用のラッパー関数

1. 汎用ターム取得関数

/**
 * 指定タクソノミーのターム一覧を取得(汎用ベース関数)
 *
 * @param string $taxonomy  対象タクソノミー名
 * @param array  $args      get_terms() に渡す追加引数
 * @return array[] {
 *   @type int    term_id
 *   @type string slug
 *   @type string name
 *   @type int    count
 *   @type string link  get_term_link() で生成したURL
 * }
 */
function taxonomy_terms_list(string $taxonomy, array $args = []): array {
    $defaults = [
        'taxonomy'   => $taxonomy,
        'hide_empty' => true,     // 投稿が1件以上あるタームのみ
        'orderby'    => 'name',
        'order'      => 'ASC',
    ];
    $query_args = array_merge($defaults, $args);

    $terms = get_terms($query_args);
    if (is_wp_error($terms) || empty($terms)) {
        return [];
    }

    $list = [];
    foreach ($terms as $t) {
        $url = get_term_link($t); // URLを生成
        if (is_wp_error($url)) {
            continue;
        }
        $list[] = [
            'term_id' => (int) $t->term_id,
            'slug'    => (string) $t->slug,
            'name'    => (string) $t->name,
            'count'   => (int) $t->count,
            'link'    => $url,
        ];
    }

    return $list;
}

/**
 * 特定タクソノミー用のラッパー関数
 *
 * @param array $args get_terms() に渡す追加引数
 * @return array[] see taxonomy_terms_list()
 */
function get_sample_terms(array $args = []): array {
    return taxonomy_terms_list('sample_taxonomy', $args);
}

2. 基本的な使い方

例えば、カスタムタクソノミー sample_taxonomy のタームを取得して一覧表示したい場合は次のように書きます。

<?php
$terms = get_sample_terms();
if (!empty($terms)): ?>
    <ul class="sample-taxonomy-list">
        <?php foreach ($terms as $term): ?>
            <li>
                <a href="<?php echo esc_url($term['link']); ?>">
                    <?php echo esc_html($term['name']); ?> (<?php echo $term['count']; ?>)
                </a>
            </li>
        <?php endforeach; ?>
    </ul>
<?php endif; ?>

出力例

<ul class="sample-taxonomy-list">
    <li><a href="https://example.com/sample/cat-news/">ニュース (5)</a></li>
    <li><a href="https://example.com/sample/cat-events/">イベント (2)</a></li>
</ul>

3. パラメータをカスタマイズ

第二引数 $args を使うことで get_terms() の引数を自由に変更できます。

非公開タームも含める

$terms = get_sample_terms([
    'hide_empty' => false,
]);

スラッグ順に並べる

$terms = get_sample_terms([
    'orderby' => 'slug',
    'order'   => 'DESC',
]);

投稿数が10件以上のタームだけ取得

$terms = array_filter(get_sample_terms(), function ($term) {
    return $term['count'] >= 10;
});

4. 他タクソノミーへの応用

汎用関数 taxonomy_terms_list() は、タクソノミー名を変えるだけで再利用できます。

// 例: product_genre タクソノミーのターム一覧
$product_terms = taxonomy_terms_list('product_genre');
foreach ($product_terms as $term) {
    echo '<p>' . esc_html($term['name']) . '</p>';
}

5. よくあるトラブルと対策

現象原因対処法
何も表示されないhide_emptytrue のため、投稿数 0 のタームが除外されているhide_emptyfalse に変更
URLが正しく生成されないget_term_link() がエラーを返しているタクソノミーの登録やスラッグを確認
並び順が想定通りにならないorderby / order の設定が正しくない公式ドキュメント を参照

6. まとめ

  • taxonomy_terms_list() で汎用化しておけば、どのタクソノミーでも簡単に利用可能
  • 特定のタクソノミーにはラッパー関数を作ると見通しが良くなる
  • $args を活用することで柔軟に取得条件を変更できる

カスタム投稿タイプやカスタムタクソノミーが多いサイトでは特に、共通化した関数が開発効率を大幅に上げてくれます。

コメント

タイトルとURLをコピーしました