LoginSignup
27
26

More than 5 years have passed since last update.

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

Posted at

※この記事は、個人ブログからのマルチポストです。

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

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

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

PHP
<?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)

27
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
26