ターム別の一覧表示

wordpress

<?php
    $taxonomy_name = 'タクソノミー名';  //カスタム投稿のタクソノミー名を入力
    $post_type = 'カスタム投稿名';    // カスタム投稿名の入力
    $args = array(
        'orderby' => 'name',
        'hierarchical' => false
        );
    $taxonomys = get_terms( $taxonomy_name, $args);
 
    if(!is_wp_error($taxonomys) && count($taxonomys)):
        foreach($taxonomys as $taxonomy):
        $url = get_term_link($taxonomy->slug, $taxonomy_name);
        $tax_posts = get_posts( array(
            'post_type' => $post_type,
            'posts_per_page' => -1, // 表示させたい記事数
            'tax_query' => array(
                array(
                    'taxonomy' => $taxonomy_name,
                    'terms' => array( $taxonomy->slug ),
                    'field' => 'slug',
                    'include_children' => true,
                    'operator' => 'IN'
                    )
                )
            ));
            if( $tax_posts ) {
?>

        <h1 id="<?php echo esc_html($taxonomy->slug); ?>"><?php echo esc_html($taxonomy->name); ?></h1> //idにタームのスラッグ名、本文にターム名を指定しています。

        <p>
            <?php foreach($tax_posts as $tax_post): ?>
            
            <?php the_content(); ?>

            <?php endforeach; wp_reset_postdata(); ?>
        </p>

<?php
            }
        endforeach;
    endif;
?>

こんな感じで出力されます。

ターム名1

コンテンツ内容

コンテンツ内容

コンテンツ内容

ターム名2

コンテンツ内容

コンテンツ内容

コンテンツ内容

色々使えます