【やりたいこと】
WordPressの、page-search.php という固定ページのテンプレートの中で、
以下のように、report・coupon 等、複数のカスタム投稿の記事を反映させています。
php
1<ul> 2 <?php 3 $args = array( 4 'post_type' => 'report', 5 ); ?> 6 <?php $the_query = new WP_Query( $args ); ?> 7 <?php if ( $the_query->have_posts() ) while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 8 <li><?php the_title(); ?></li> 9 <?php endwhile;?> 10 <?php wp_reset_postdata(); ?> 11</ul> 12<ul> 13 <?php 14 $args = array( 15 'post_type' => 'coupon', 16 ); ?> 17 <?php $the_query = new WP_Query( $args ); ?> 18 <?php if ( $the_query->have_posts() ) while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 19 <li><?php the_title(); ?></li> 20 <?php endwhile;?> 21 <?php wp_reset_postdata(); ?> 22</ul>
このURLのサイトを参考にして、
pre_get_postsというものを使用して、
例えば、ランダムで記事を表示・各記事数を4件表示というふうにすると、
functions.phpに、以下のように追加しましたが、効きません。
php
1function change_posts_per_page($query) { 2 /* 管理画面,メインクエリに干渉しないために必須 */ 3 if( is_admin() || ! $query->is_main_query() ){ 4 return; 5 } 6 7 /* searchページの表示件数を4件にする */ 8 if ( $query->is_page('search') ) { 9 $query->set( 'posts_per_page', '4' ); 10 $query->set( 'orderby', 'rand' ); 11 return; 12 } 13 14} 15add_action( 'pre_get_posts', 'change_posts_per_page' );
argsの中にそのまま 'posts_per_page' => -1, のように条件を追加するのではなく、pre_get_postsを使用したいです。
どなたか教えていただけないでしょうか?
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/01/06 07:37
2018/07/14 11:04