WordPress 新着記事一覧でカテゴリー名に個別の背景色をつけて表示する
カテゴリーごとのCSSクラスを付与する
index.php, home.php, archive.php などの記事ループ内で、各記事のカテゴリーに応じたクラス名を出力する。
投稿ループ内の書き方
<?php
$categories = get_the_category();
if ( ! empty( $categories ) ) {
foreach ( $categories as $category ) {
echo '<span class="category-label category-' . esc_attr( $category->slug ) . '">' . esc_html( $category->name ) . '</span>';
}
}
?>
例:「ニュース」カテゴリー(スラッグ: news)に category-news というクラスが付与されます。
実用例
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
);
$the_query = new WP_Query($args);
?>
<?php if ($the_query->have_posts()): ?>
<ul>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<li>
<span class="date">
<time datetime="<?php echo esc_attr(get_the_time('Y-m-d')); ?>">
<?php echo esc_html(get_the_time('Y年m月d日')); ?>
</time>
</span>
<?php
$categories = get_the_category();
if ( ! empty($categories) ) :
$cat = $categories[0];
$cat_name = $cat->cat_name;
$cat_slug = $cat->category_nicename;
?>
<span class="category-label category-<?php echo esc_attr($cat_slug); ?>">
<?php echo esc_html($cat_name); ?>
</span>
<?php endif; ?>
<span class="post_title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></span>
</li>
<?php endwhile; ?>
</ul>
<?php else: ?>
<p>まだ投稿がありません。</p>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
複数カテゴリーを全部表示したい場合
<?php
$categories = get_the_category(); // 投稿のカテゴリーを取得
if ( ! empty($categories) ) : // カテゴリーが存在するかチェック
foreach ($categories as $cat) : // 各カテゴリーに対して処理
$cat_name = $cat->cat_name; // カテゴリー名
$cat_slug = $cat->category_nicename; // スラッグ(クラス名用)
?>
<!-- 出力されるHTML -->
<span class="category-label category-<?php echo esc_attr($cat_slug); ?>">
<?php echo esc_html($cat_name); ?>
</span>
<?php
endforeach;
endif;
?>
おまけのCSS・・
共通スタイル
.category-label {
padding: 4px 8px;
border-radius: 3px;
font-size: 0.8em;
color: #fff;
display: inline-block;
margin-right: 6px;
}
カテゴリー別の色
.category-news {
background-color: #0073aa;
}
.category-blog {
background-color: #46b450;
}
.category-event {
background-color: #d54e21;
}
/* スラッグが日本語の場合(例:未分類) */
.category-未分類 {
background-color: #888;
}
例:
- 「ニュース」カテゴリー(スラッグ: news): category-news
- 「ブログ」カテゴリー(スラッグ: blog): category-blog
- 「イベント」カテゴリー(スラッグ: event): category-event
