BLOGブログ
WordPressのカスタム投稿で特定のタクソノミータームを除外して表示する方法
WordPress でカスタム投稿を使っていると、「未分類」などの「特定のタクソノミータームを除外して投稿を表示したい」というケースが出てきます。
このような場合、WP_Query
の tax_query
を使うことで簡単に特定のタームを除外できます!
基本構文
$args = array(
’post_type’ => ‘custom_post_type’, // カスタム投稿タイプを指定
’posts_per_page’ => 10, // 表示する投稿数
’tax_query’ => array(
array(
’taxonomy’ => ‘custom_taxonomy’, // 除外したいタクソノミーのスラッグ
‘field’ => ‘slug’, // タームの指定方法(’slug’ or ‘term_id’)
‘terms’ => array(‘exclude-term’), // 除外するターム(スラッグ)
‘operator’ => ‘NOT IN’, // ‘NOT IN’ で除外する
),
),
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
?>
<h2><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></h2>
<?php
endwhile;
wp_reset_postdata();
else :
echo ‘<p>該当する投稿はありません。</p>’;
endif;
?>
複数のタームを除外したいときは'terms' => array('internal', 'private')
のように複数指定OK!
CONTACTお問い合わせ
サービスに関するお問い合わせやお見積もり・ご相談などお気軽にご相談ください。