【WordPress】カスタム投稿タイプの記事の一覧を特定のカテゴリのみ非表示で表示させる

電脳備忘録

下記の例では、カスタム投稿タイプ「news」のカテゴリ「news-cat」のスラッグ「medical」以外の記事を一覧表示させている。
ページ数を取得してセットしてあげないとページャーがまともに動かない。それを知らずに手間取ったが今回も攻略できたのでよしとしよう・・・。

//archive-news.php
<ul class="post-list">
<?php
//ページ数の取得
if (get_query_var('paged')) {
$paged = get_query_var('paged');
} else {
$paged = 1;
}
$the_query = new WP_Query();
//条件設定
$args = array(
'post_type' => 'news',
'paged' => $paged,
'tax_query' => array(
array(
'taxonomy' => 'news-cat',
'field' => 'slug',
'terms' => 'medical',
'operator'  => 'NOT IN'
)
)
);
$the_query->query($args);
if($the_query->have_posts()): while($the_query->have_posts()) : $the_query->the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; ?>
</ul>
<!-- ページャー  -->
<div class="pager-nav">
<?php global $wp_rewrite;
$paginate_base = get_pagenum_link(1);
if (strpos($paginate_base, '?') || ! $wp_rewrite->using_permalinks()) {
$paginate_format = '';
$paginate_base = add_query_arg('paged', '%#%');
} else {
$paginate_format = (substr($paginate_base, -1 ,1) == '/' ? '' : '/') .
user_trailingslashit('page/%#%/', 'paged');;
$paginate_base .= '%_%';
}
echo paginate_links( array(
'base' => $paginate_base,
'format' => $paginate_format,
'total' => $wp_query->max_num_pages,
'mid_size' => 5,
'current' => ($paged ? $paged : 1),
));
?>
</div>
<!-- /ページャー -->

ページャーを動かすための呪文をfunction.phpにかく。

function change_posts_per_page($query) {
if ( is_admin() || ! $query->is_main_query() ) {
return;
}
if ( $query->is_post_type_archive('news')){//ここでタクソノミー名を設定
$query->set( 'posts_per_page', '5' );//ここで表示件数を設定
}
}
add_action( 'pre_get_posts', 'change_posts_per_page' );

広告

ブログの維持費に充てるでございます・・・。