特定の投稿タイプを除外して全ての記事を表示する方法

2024.06.18

以下のようにすれば特定の記事を除外して(例えば、固定ページやWPデフォルトの登校)公開されてる記事だけを表示できます。

<?php
	$exclude_post_types = array('page','post'  );// 除外したい投稿タイプを配列に設定(固定ページとデフォルト登校は必要ない。他に指定したいカスタム投稿がある場合はここに記述)
	$all_post_types = get_post_types(array('public' => true), 'names');// 利用可能な公開されている全てのカスタム投稿タイプを取得
	$postType = array_diff($all_post_types, $exclude_post_types);// 除外したい投稿タイプを指定して、記事を取得

	$args = array(
		'post_type' => $postType,
		'posts_per_page' => 5,
		'paged' => $paged,
	);
	$the_query =  new WP_Query($args);

	//以下はwordpressのループ文で記事を呼び出す
?>

<?php if ( $the_query->have_posts() ) : ?>
	<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
		記事情報html
	<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
totop Page Top