home.phpなどの投稿ページに、タクソノミーのターム(カテゴリー)ごとに投稿の一覧または子カテゴリーを表示するソースです。
<div class="box">
<?php
$args = array(
'parent' => 0,
'hierarchical' => 0,
'order' => 'ASC'
);
$taxonomy_name = 'タクソノミー名';
$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 );
?>
<div class="contentbox01">
<h2 id="<?php echo esc_html($taxonomy->slug); ?>" class="h2_style01"><?php echo esc_html($taxonomy->name); //タームタイトル?></h2>
<div class="contentbox01_in">
<table class="table_style01">
<?php
/**
* お知らせ等の一覧を取得
*
*/
$args = array(
'post_type' => 'カスタム投稿名',
'posts_per_page' => 10, //新着順に10件表示
'orderby' => 'post_date',
'order' => 'DESC',
'post_status' => 'publish',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'タクソノミー名',
'field' => 'slug',
'terms' => $taxonomy->slug,
'include_children' => true,
'operator' => 'IN'
),
)
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ):
?>
<?php
$term_id = $taxonomy->term_id;
$children = get_term_children( $term_id, $taxonomy_name );
if ( $children ): //子タームを持つ場合にはタームの一覧を表示
?>
<?php
$term_id = $taxonomy->term_id;
$taxonomy_name = 'タクソノミー名';
$termchildren = get_term_children( $term_id, $taxonomy_name );
foreach ( $termchildren as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<tr><td><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a><td></th>';
}
?>
<?php else: ?> //子タームを持たない場合には投稿の一覧を表示
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<tr>
<th>
<?php the_time('Y.m.d'); ?>
</th>
<td>
<?php
$cf_important = get_field( 'important' ); //ACFで作成したチェックボックス
if ( $cf_important == '表示する' ) {
echo '<span class="important01">重要</span>';
} else {
echo ' ';
}
?>
<?php if(get_field('important')): ?>
<span class="important01">重要</span>
<?php endif ;?>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</td>
</tr>
<?php
endwhile;
?>
<?php endif; ?>
<?php
endif;
wp_reset_postdata();
?>
</table>
</div>
<div class="btnbox01">
<a href="<?php echo esc_url( home_url( '/' ) ); ?><?php echo esc_html($taxonomy->slug); ?>/">一覧へ</a>
</div>
</div>
<?php endforeach; endif; wp_reset_postdata(); ?>
</div>
<!-- box -->









