Advanced Custom Fields(ACF)プラグインを使用してカスタムフィールドを追加し、カテゴリーに画像を設定する手順を以下に示します。
1. ACFでカスタムフィールドを追加する
まず、WordPressの管理画面からACFを使用して、カテゴリーにカスタムフィールドを追加します。
- フィールドグループの作成
- WordPress管理画面の左側メニューから「Custom Fields」 > 「Add New」を選択します。
- フィールドグループの名前を入力(例:「Category Image」)。
 
- フィールドの追加
- フィールドラベル: Category Image
- フィールド名: category_image
- フィールドタイプ: Image
 
- フィールドラベル: 
- 表示ルールの設定
- 「Show this field group if」セクションで、以下のように設定します。
- Taxonomyが- 等しい- カテゴリー
 
 
- 「Show this field group if」セクションで、以下のように設定します。
- フィールドグループの保存
- 「Publish」ボタンをクリックしてフィールドグループを保存します。
 
2. メディアアップローダーのコードは不要
ACFプラグインを使用する場合、メディアアップローダーのコードを自分で追加する必要はありません。ACFが自動的にメディアアップローダーを提供してくれます。
3. カスタムフィールドの画像を表示するコード
ACFで追加したカスタムフィールドの画像を表示するためのコードはそのままで使用します。以下のコードをカテゴリー一覧ページのテンプレートファイル(通常はarchive.phpまたはcategory.php)に追加します。
phpコードをコピーする<?php get_header(); ?>
<div id="primary" class="content-area">
    <main id="main" class="site-main">
        <?php if ( have_posts() ) : ?>
            <header class="page-header">
                <?php
                // カテゴリーのカスタムフィールド画像を取得して表示
                $term = get_queried_object();
                $category_image_id = get_field('category_image', 'category_' . $term->term_id);
                if ($category_image_id) {
                    $category_image_url = wp_get_attachment_url($category_image_id);
                    if ($category_image_url) {
                        echo '<div class="category_bnr"><img src="' . esc_url($category_image_url) . '" alt="' . single_cat_title('', false) . '"></div>';
                    }
                }
                ?>
                <h1 class="page-title"><?php single_cat_title(); ?></h1>
                <?php
                the_archive_description( '<div class="taxonomy-description">', '</div>' );
                ?>
            </header><!-- .page-header -->
            <?php
            /* Start the Loop */
            while ( have_posts() ) :
                the_post();
                /*
                 * Include the Post-Format-specific template for the content.
                 * If you want to override this in a child theme, then include a file
                 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                 */
                get_template_part( 'template-parts/content', get_post_format() );
            endwhile;
            the_posts_navigation();
        else :
            get_template_part( 'template-parts/content', 'none' );
        endif;
        ?>
    </main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
まとめ
ACFプラグインを使用することで、WordPressのカテゴリーにカスタムフィールドを簡単に追加し、その画像をカテゴリー一覧ページで表示することができます。以下の手順で実装しました。
- ACFでカスタムフィールドを追加
- カテゴリーに画像フィールドを追加。
 
- コードの修正
- ACFの機能を利用するために必要なコードをテンプレートファイルに追加。
 
これで、カテゴリーごとに異なる画像を設定し、カテゴリー一覧ページに表示することができます。是非お試しください。