Advanced Custom Fields でカテゴリーのアイコンや背景色を設定

情報を追記している場合はありますが、古い情報を訂正はしていませんので、公開年月日を参照してください。プラグイン・タグ、いずれもワードプレス・PHPのバージョン等によって動作しない場合もあります。

カテゴリーの表示を画像で、カテゴリーごとにアイコン風に背景色を変えたいという要望で、Advanced Custom Fields でカテゴリー・タクソノミーにカスタムフィールドを設置。
値の取得はthe_field(‘フィールド名’, ‘category_1’); のように。数字はID。

タクソノミー xxxxx にアイコンのアップロード欄を設けて、画像を表示

<?php
$terms = wp_get_object_terms( $post->ID, 'xxxxx' );
if ( $terms AND !is_wp_error( $terms ) ) {
   foreach ( $terms as $term ) {
if (get_field('フィールド名', 'xxxxx_' . $term->term_id )) { $attachment_id = get_field('フィールド名', 'xxxxx_' . $term->term_id );$size = 'full';$image = wp_get_attachment_image_src( $attachment_id, $size );
      echo '<a href="' . get_term_link( $term, $term->taxonomy ) . '"><img src="' . $image[0] . '" width="' . $image[1] . '" height="' . $image[2] . '" alt="' . $term->name . '" /></a>';
}  } } ?>

最下層のカテゴリーを取得して、設定された背景色を付ける

<?php $cats = get_the_category();
$current_cat = '';
foreach ( $cats as $cat ) {
	if ( ! $current_cat || cat_is_ancestor_of( $current_cat, $cat ) ) {
		$current_cat = $cat;
	}
} ?><span class="cate" style="background:<?php the_field('フィールド名', 'category_' . $current_cat->cat_ID ); ?>;"><?php echo $current_cat->cat_name; ?></span>

その他のAdvanced Custom Fields に関する記事一覧

Advanced Custom Fields に関する記事一覧ページへ