WordPressでposts_per_pageの設定が効かない場合の対処法【確定版】


この記事では、




WordPressでposts_per_pageの設定が効かない場合の対処法【確定版】」

 



を紹介致します。


答え:「固定記事の表示の処理」と「固定記事以外の記事の処理」を分ける

上記の記事で紹介した方法で、一時的にうまくいったのですが、2週間後ぐらいに再び、新着記事の表示数が、こちらの意図通りにならなくなりました。

そこで、ググって色々試してみたところ、下記の方法が最善であることが分かりました。

2020年7月31日現在、上記で紹介されているコードを少しだけ修正して、使用しています。

具体的なコードは、以下の通りです(固定記事を含めて記事を常に4つ並べて表示)。

<?php 
$list_cnt = 4; //表示させたい件数
$sticky = get_option('sticky_posts'); //先頭固定の記事
if ( !empty($sticky) ) $list_cnt -= count($sticky); //もし先頭固定の記事があったら、その件数を「$list_cnt」の値から引く
if ( count($sticky) > 0 ):
	$the_query = new WP_Query(array(
		'posts_per_page'=>4,
		'post__in' => $sticky,
	));?>
	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<div>
繰り返したい処理
</div>

	<?php endwhile; ?>
<?php endif; ?>
<?php if ( $list_cnt > 0 ):
	$the_query = new WP_Query(array(
		'posts_per_page' => $list_cnt,
		'ignore_sticky_posts' => 1,
	));?>
	<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<div>
繰り返したい処理
</div>  		
		
	<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>


ほとんどWEB制作者の備忘録さんのコードのコピペですが、

<?php if ( $list_cnt > 0 ): //先頭固定以外の記事の表示

と元々は記述されていた箇所を、

<?php if ( $list_cnt > 0 ):

という風に、コメントを削除すると、なぜかうまくいきました^^

コメントがある状態だと、私の環境だとエラーが起きます(使用しているサーバーはロリポップサーバーです)。