親カテゴリーと子カテゴリを階層化する

  • 開発メモ
function category_posts_with_children_shortcode($atts) {
    $atts = shortcode_atts(
        array(
            'posts_per_page' => -1, // 表示する投稿数
        ),
        $atts,
        'category_posts_with_children'
    );

    // 親カテゴリーを取得
    $args = array(
        'taxonomy' => 'category',
        'parent'   => 0, // 親カテゴリー(親カテゴリのみ)
        'hide_empty' => false, // 空のカテゴリーも表示
    );
    $parent_categories = get_categories($args);

    $output = '';

    foreach ($parent_categories as $parent_category) {
        // 親カテゴリー名を表示
        $output .= '<h2>' . esc_html($parent_category->name) . '</h2>';

        // 子カテゴリーを取得
        $child_categories = get_categories(array(
            'taxonomy' => 'category',
            'parent' => $parent_category->term_id,
            'hide_empty' => false,
        ));

        foreach ($child_categories as $child_category) {
            // 子カテゴリー名を表示
            $output .= '<h3>' . esc_html($child_category->name) . '</h3>';

            // 子カテゴリーの投稿を取得
            $args = array(
                'category_name' => $child_category->slug, // 子カテゴリーのスラッグ
                'posts_per_page' => $atts['posts_per_page'], // 投稿数
                'orderby' => 'title', // タイトル順
                'order' => 'ASC', // 昇順
            );

            $query = new WP_Query($args);

            if ($query->have_posts()) {
                $output .= '<ul>';
                while ($query->have_posts()) {
                    $query->the_post();
                    $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
                }
                $output .= '</ul>';
            } else {
                $output .= '<p>No posts found in this category.</p>';
            }

            wp_reset_postdata(); // クエリのリセット
        }
    }

    return $output;
}
add_shortcode('category_posts_with_children', 'category_posts_with_children_shortcode');