カテゴリー別の投稿一覧を自動生成(HTML版)する方法
この記事では、WordPressで投稿一覧を作成する方法を解説します。
1 実装のポイント
- functions.php にコードを追加してショートコード化
- 親カテゴリーには子カテゴリーの記事を含めず、重複を防止
- CSSで見やすいリストデザインを調整
2 functions.php にコードを追加
以下のコードを functions.php に追加します。ショートコード [category_sitemap] を投稿や固定ページに挿入すれば、サイトマップが自動生成されます。
// ------------------------------------------------------------
// カテゴリー別サイトマップ(親はタイトルのみ、子カテゴリに記事表示)
// ------------------------------------------------------------
function category_sitemap_shortcode() {
$output = '<div class="sitemap">';
// 親カテゴリー取得
$parent_categories = get_categories(array(
'parent' => 0,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false
));
foreach ($parent_categories as $parent) {
$output .= '<h2 class="sitemap-parent">' . esc_html($parent->name) . '</h2>';
// 子カテゴリーを取得
$child_categories = get_categories(array(
'parent' => $parent->term_id,
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false
));
if ($child_categories) {
// 子カテゴリがある場合 → 子カテゴリの記事のみ表示
foreach ($child_categories as $child) {
$output .= '<h3 class="sitemap-child">' . esc_html($child->name) . '</h3>';
$output .= '<ul class="sitemap-list">';
$posts = get_posts(array(
'category' => $child->term_id,
'numberposts' => -1,
'orderby' => 'date',
'order' => 'DESC'
));
if ($posts) {
foreach ($posts as $post) {
$output .= '<li><a href="' . get_permalink($post->ID) . '">' . esc_html(get_the_title($post->ID)) . '</a></li>';
}
} else {
$output .= '<li>記事はまだありません</li>';
}
$output .= '</ul>';
}
} else {
// 子カテゴリがない場合(=末端カテゴリなら記事表示)
$parent_posts = get_posts(array(
'category' => $parent->term_id,
'numberposts' => -1,
'orderby' => 'date',
'order' => 'DESC'
));
if ($parent_posts) {
$output .= '<ul class="sitemap-list">';
foreach ($parent_posts as $post) {
$output .= '<li><a href="' . get_permalink($post->ID) . '">' . esc_html(get_the_title($post->ID)) . '</a></li>';
}
$output .= '</ul>';
}
}
}
$output .= '</div>';
return $output;
}
add_shortcode('category_sitemap', 'category_sitemap_shortcode');
補足:
- ショートコード
[category_sitemap]を記事や固定ページに挿入するだけでサイトマップが表示されます。 - 親カテゴリーに子カテゴリがある場合は、記事リストを表示せずタイトルのみ出力します。
記事内で表示する場合:
[category_sitemap]
3 汎用CSS
/* -----------------------------
* カテゴリー別サイトマップ
* ----------------------------- */
/* サイトマップ全体 */
.sitemap {
margin: 20px 0; /* 上下に20pxの余白を作る */
padding: 15px; /* 内側に15pxの余白を作り、文字や要素が端にくっつかないようにする */
}
/* 親カテゴリー */
.sitemap-parent {
font-size: 1.4em; /* 文字を通常の1.4倍にして強調 */
margin-top: 20px; /* 上に20pxの余白を作り、前の要素と間隔を空ける */
border-bottom: 2px solid #00aaff; /* 下に2pxの水色線を引き、見出し風にする */
padding-bottom: 5px; /* 下線と文字がくっつかないように5pxの余白を入れる */
}
/* 子カテゴリー */
.sitemap-child {
font-size: 1.1em; /* 文字を少し大きめにして読みやすくする */
margin: 15px 0 5px; /* 上15px・下5pxの余白でリスト間の間隔を調整 */
color: #333; /* 黒より柔らかい濃いグレーの文字色にする */
}
/* 記事リスト */
.sitemap-list {
margin-left: 20px; /* 左に20pxずらして階層構造を分かりやすくする */
list-style-type: disc; /* 項目の先頭に黒丸(●)を表示する */
}
4 完成イメージ
5 まとめ
- functions.phpにコードを追加 → ショートコード
[category_sitemap]でサイトマップ表示 - 親カテゴリーはタイトルだけ、子カテゴリーには記事リストを表示して重複を回避
- JavaScript不要でシンプルに実装できる


