記事一覧にカテゴリを表示する

電脳備忘録

本記事のソースコードの利用によって生じた損害について、当方は一切の責任を負いません。ご自身の判断と責任のもとで参照・ご利用ください。

カテゴリが空白かチェックして、記事ごとのカテゴリを表示する。こんな感じ2025-03-30-001.jpg

とりあえずこれでOK。

<ul>
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish'
);
$query_post_list = new WP_Query($args);
if ($query_post_list->have_posts()) :
while ($query_post_list->have_posts()) : $query_post_list->the_post();
// 各記事のカテゴリを取得 - ループの中で取得する
$categories = get_the_category();
$category_name = '';
if (!empty($categories)) {
$category_name = $categories[0]->name; // 最初のカテゴリを使用
}
?>
<li><?php echo $category_name; ?></li>
<?php endwhile; endif; ?>
</ul>

もっと簡単に表示する方法があるのかもしれない。

Older
Dark
Light
menu