0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

get_term_by() 関数について

Last updated at Posted at 2025-02-10

get_term_by() はWordPressのタクソノミー(カテゴリーや、カスタムタクソノミーなど)からタームを1つ取得する関数です。

基本的な構文

get_term_by( string $field, mixed $value, string $taxonomy, string $output = OBJECT, string $filter = 'raw' )

必須パラメータ

  • $field 検索するフィールド
    'id': タームID
    'slug': スラッグ名
    'name': ターム名
    'term_taxonomy_id': タームタクソノミーID

  • $value  検索する値
    $fieldで指定したフィールドに対応する検索値
    例:スラッグで検索する場合はスラッグ名を指定

  • $taxonomy タクソノミー名
    検索対象のタクソノミー
    例:'category'(通常のカテゴリー)、'post_tag'(タグ)など

オプションパラメータ

  • $output - 出力形式(デフォルト:OBJECT)
    OBJECT: オブジェクトとして返す
    ARRAY_A: 連想配列として返す
    ARRAY_N: 数値配列として返す

  • $filter - フィルタリング方法(デフォルト:'raw')
    'raw': フィルタリングなし
    'display': 表示用にフィルタリング

// IDで取得
$term = get_term_by('id', 123, 'category');

// スラッグで取得
$term = get_term_by('slug', 'news', 'category');

// 名前で取得
$term = get_term_by('name', 'ニュース', 'category');

// 配列として取得
$term = get_term_by('id', 123, 'category', ARRAY_A);
// 成功時の戻り値(オブジェクトの場合(デフォルト))
stdClass Object (
    [term_id] => 123
    [name] => ニュース
    [slug] => news
    [term_group] => 0
    [term_taxonomy_id] => 123
    [taxonomy] => category
    [description] => ニュースカテゴリーの説明
    [parent] => 0
    [count] => 5
)

// 失敗時
false
// オプションパラメータ デフォルトの使用($outputを指定しない)
$term = get_term_by('slug', 'news', 'category');
echo gettype($term); // "object" と出力

// プロパティへのアクセス方法
echo $term->name;    // オブジェクトとしてアクセス可能
echo $term->term_id;
echo $term->slug;

// 比較:配列として取得する場合
$term_array = get_term_by('slug', 'news', 'category', ARRAY_A);
echo gettype($term_array); // "array" と出力

// 配列の場合のアクセス方法
echo $term_array['name'];    // 配列としてアクセス
echo $term_array['term_id'];
echo $term_array['slug'];

特に指定しない場合は自動的にオブジェクトとして取得でき、-> を使ってプロパティにアクセスできます。

エラーハンドリング

$term = get_term_by('slug', 'news', 'category');
if ($term) {
    // 成功時の処理
    echo $term->name;
} else {
    // 失敗時の処理
    echo 'タームが見つかりませんでした';
}

よく使われるプロパティ

term_id: タームのID
name: ターム名
slug: スラッグ
taxonomy: タクソノミー名
description: 説明
parent: 親タームのID
count: このタームに属する投稿数

この関数は特定のカテゴリーやタームを取得する際に非常に便利で、WordPressの投稿やカスタム投稿タイプの分類・整理に広く使用されています。

子タームの取得

基本的な構文

get_terms( array(
    'taxonomy' => 'タクソノミー名',
    'parent' => 親タームのID,
    'hide_empty' => true/false,
    // その他のパラメータ...
));

主要なパラメータの説明

$args = array(
    // 必須パラメータ
    'taxonomy' => 'カテゴリーの種類',  // 例:'category', 'post_tag', カスタムタクソノミー名
    
    // よく使用される任意パラメータ
    'parent' => 0,                    // 親タームのID(0は最上位)
    'child_of' => 0,                  // 特定のタームの下位階層全て
    'hide_empty' => true,             // 投稿のないタームを非表示にする
    'orderby' => 'name',              // ソートの基準
    'order' => 'ASC',                 // ソート順
    'number' => 0,                    // 取得する数(0は無制限)
    'offset' => 0,                    // スキップする数
    'slug' => '',                     // 特定のスラッグ
    'name' => '',                     // 特定の名前
)

使用例

  • 基本的な子ターム取得
// 親カテゴリーのIDが123の子カテゴリーを取得
$child_terms = get_terms(array(
    'taxonomy' => 'category',
    'parent' => 123,
    'hide_empty' => false
));
  • 複数のタクソノミーから取得
$terms = get_terms(array(
    'taxonomy' => array('category', 'post_tag'),
    'parent' => 0
));
  • 特定の順序で取得
$terms = get_terms(array(
    'taxonomy' => 'category',
    'orderby' => 'name',  // name, id, count など
    'order' => 'DESC',    // ASC or DESC
    'parent' => 123
));
  • 投稿のあるタームのみ取得
$terms = get_terms(array(
    'taxonomy' => 'category',
    'hide_empty' => true,
    'parent' => 123
));
  • エラーハンドリング
$terms = get_terms($args);
if (!empty($terms) && !is_wp_error($terms)) {
    foreach ($terms as $term) {
        echo $term->name;  // ターム名を表示
    }
} else {
    echo '子タームが見つかりませんでした';
}
  • 戻り値の利用
foreach ($terms as $term) {
    // 利用可能なプロパティ
    echo $term->term_id;       // タームID
    echo $term->name;          // ターム名
    echo $term->slug;          // スラッグ
    echo $term->description;   // 説明
    echo $term->parent;        // 親タームのID
    echo $term->count;         // 投稿数
    
    // タームのリンクを取得
    $term_link = get_term_link($term);
    echo "<a href='{$term_link}'>{$term->name}</a>";
}

parent と child_of の違い

parent: 直接の子タームのみ取得
child_of: 指定したタームの下位階層全てを取得

// 直接の子タームのみ
$direct_children = get_terms(array(
    'taxonomy' => 'category',
    'parent' => 123
));

// 全ての子孫ターム
$all_children = get_terms(array(
    'taxonomy' => 'category',
    'child_of' => 123
));

親子カテゴリー取得サンプル

<?php
/*
Template Name: カテゴリー一覧
*/

get_header(); ?>

<div class="container mx-auto px-4">
    <div class="main-content py-8">
        <h1 class="text-2xl font-bold mb-6">カテゴリー一覧</h1>

        <?php
        // 親カテゴリーのみを取得
        $parent_terms = get_terms(array(
            'taxonomy' => 'category',  // タクソノミー名
            'parent' => 0,            // 親カテゴリーのみ(親を持たないカテゴリー)
            'hide_empty' => false     // 投稿が無いカテゴリーも表示
        ));

        // エラーチェックと空チェック
        if (!is_wp_error($parent_terms) && !empty($parent_terms)) {
            foreach ($parent_terms as $parent_term) {
                // 親カテゴリーの情報を表示
                ?>
                <div class="parent-category mb-8">
                    <h2 class="text-xl font-semibold mb-4">
                        <?php echo esc_html($parent_term->name); ?>
                    </h2>
                    
                    <?php if (!empty($parent_term->description)) : ?>
                        <p class="text-gray-600 mb-4">
                            <?php echo esc_html($parent_term->description); ?>
                        </p>
                    <?php endif; ?>

                    <?php
                    // 子カテゴリーを取得
                    $child_terms = get_terms(array(
                        'taxonomy' => 'category',
                        'parent' => $parent_term->term_id,
                        'hide_empty' => false
                    ));

                    // 子カテゴリーが存在する場合
                    if (!is_wp_error($child_terms) && !empty($child_terms)) {
                        ?>
                        <div class="child-categories pl-6">
                            <ul class="list-disc">
                                <?php foreach ($child_terms as $child_term) : ?>
                                    <li class="mb-2">
                                        <a href="<?php echo esc_url(get_term_link($child_term)); ?>" 
                                           class="text-blue-600 hover:text-blue-800">
                                            <?php echo esc_html($child_term->name); ?>
                                            <span class="text-gray-500">
                                                (<?php echo $child_term->count; ?>)
                                            </span>
                                        </a>
                                        <?php if (!empty($child_term->description)) : ?>
                                            <p class="text-sm text-gray-500 mt-1">
                                                <?php echo esc_html($child_term->description); ?>
                                            </p>
                                        <?php endif; ?>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php
                    }
                    ?>
                </div>
                <?php
            }
        } else {
            ?>
            <p class="text-gray-600">カテゴリーが見つかりませんでした。</p>
            <?php
        }
        ?>
    </div>
</div>

<?php get_footer(); ?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?