MENU

WordPressの固定ページで、WP_Queryで記事を取得するもページネーション(the_posts_pagination)がうまく動作しない場合の解決方法。

ちょいと調べてみたけど、結構その対応手段がネットに公開されていなかったので、ソース調べてみた。

get_the_posts_pagination() 内で、$GLOBALS['wp_query']->max_num_pages が1以上じゃないと処理をしないのに、固定ページ内で WP_Query を回しても $GLOBALS['wp_query']->max_num_pages には値が入っていないのが原因。

なので、自分でぶっ込んでやれば良いみたい。

<?php
//pagedに値をセットするのを忘れずに!
$the_query = new WP_Query( array(
  'paged'       => get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1,
  'post_type'   => 'post'
) ); ?>

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

<!--ここで記事を表示-->

<?php	endwhile; ?>

<?php
//ページネーション表示前に$GLOBALS['wp_query']->max_num_pagesに値をセット
$GLOBALS['wp_query']->max_num_pages = $the_query->max_num_pages;
the_posts_pagination();
wp_reset_postdata();
?>

こんな感じ。(2016年1月28日現在。WordPressのバージョンは4.4.1)