カスタム投稿に別のカスタム投稿も表示させる


WordPress の single のページにおいて、カスタム投稿をメインに表示させ、ページ下方に別のカスタム投稿の内容を表示させたい!

という事案があり、その方法を残しておきたく。。。

◆メインのカスタム投稿
  • post_type : cusmain
◆サブのカスタム投稿
  • post_type : cussub
◆タクソノミー
  • name : tax

上2つのカスタム投稿に上のタクソノミーを関連させる。この辺の作業は、Custom Post Type UI で。

term を作り、メインのカスタム投稿の記事とサブのカスタム投稿の記事で同じ term を選択する。要は term が2つの記事の紐付け役になる。

single ページは、メインのカスタム投稿向けとして single-cusmain.php を作成。あとは、tax_query を使った以下のようなコードにする。

if( have_posts() ):
while( have_posts() ) : the_post();
the_content();
$term = get_the_terms( $post->id, 'tax' );
$array = [
	'post_type' => 'cussub',
	'tax_query' => array(
		array(
			'taxonomy' => 'tax',
			'field' => 'slug',
			'terms' => $term[0]->slug
		)
	)
];
$results = get_posts( $array );
var_dump( $results );
endwhile; endif;