備忘録として。
目次
✅ 1. functions.php にショートコードを追加
まずは、以下のコードをテーマの functions.php に追加します:
// HTMLサイトマップ用のショートコード
function custom_html_sitemap() {
$output = '';
// 固定ページ一覧
$output .= '<h2>固定ページ</h2><ul>';
$pages = get_pages(array('sort_column' => 'menu_order'));
foreach ($pages as $page) {
$output .= '<li><a href="' . get_permalink($page->ID) . '">' . esc_html($page->post_title) . '</a></li>';
}
$output .= '</ul>';
// 投稿(カテゴリー別)
$output .= '<h2>投稿</h2>';
$categories = get_categories();
foreach ($categories as $category) {
$output .= '<h3>' . esc_html($category->name) . '</h3><ul>';
$posts = get_posts(array(
'category' => $category->term_id,
'numberposts' => -1,
));
foreach ($posts as $post) {
$output .= '<li><a href="' . get_permalink($post->ID) . '">' . esc_html($post->post_title) . '</a></li>';
}
$output .= '</ul>';
}
return $output;
}
add_shortcode('custom_sitemap', 'custom_html_sitemap');
✅ 2. 固定ページを作成し、ショートコードを記述
WordPress管理画面 → 「固定ページ」→「新規追加」
ページタイトル:サイトマップ
本文に以下を記入:
[custom_sitemap]
「公開」すると、固定ページと投稿一覧がカテゴリごとに表示されます。
✅ 出力される内容の例(シンプルなHTML)
<h2>固定ページ</h2>
<ul>
<li><a href="/about">会社概要</a></li>
<li><a href="/contact">お問い合わせ</a></li>
</ul>
<h2>投稿</h2>
<h3>ブログ</h3>
<ul>
<li><a href="/post1">記事タイトル1</a></li>
<li><a href="/post2">記事タイトル2</a></li>
</ul>
✅ カスタマイズのヒント
get_pages()やget_posts()に条件を追加すれば非公開ページを除いたり、投稿数を制限したりできます。- 出力に
<ul>ではなく<div>を使えば、デザインを柔軟にカスタマイズ可能。 - 必要に応じてタグ別・カスタム投稿タイプにも対応可能です。
コメント