カテゴリー
WordPress

見出しと所属する記事の一覧表示

人は忘れる。そして同じところで躓く。今回もそうだった。従って忘れないうちにメモをしておく。

以下はカスタム投稿で固定ページテンプレートを使用する際、見出し(タクソノミーターム)と所属する記事を一覧表示させたいときに使用した。2つのループを使用している。説明不足だが、自分への忘備録なのでご理解いただきたい。

<!-- パラメータ取得&見出しループスタート -->
<?php $terms = get_terms('タクソノミー名'); foreach ( $terms as $term ) { $terms_name = $term->name;
$terms_slug = $term->slug;
?>

<h2><?php echo $terms_name;?></h2>

<!-- 入れ子 -->
<?php $args = array( 'post_type' => 'ポストタイプ名',
	'tax_query' => array(
		array(
			'taxonomy' => 'タクソノミー名',
			'field'    => 'slug',
			'terms'    => $terms_slug,
		),
	),
);
$the_query = new WP_Query( $args ); ?>

<ul>
<?php if ( $the_query->have_posts() ) : ?>
	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

		
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>


	<?php endwhile; ?>
	<?php wp_reset_postdata(); ?>
<?php else : ?>
	

<?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?>

<?php endif; ?>
</ul>

<!-- 入れ子ここまで -->
<?php } ?>
<!-- 見出しループここまで -->