2016-09-28 9 views
3

私は、「pre_get_posts」フックを使用して「friends」カテゴリの投稿のみを表示するmy wordpress myThemeフォルダに非常に単純なindex.phpファイルを持っています。しかし、if条件の$ query-> is_main_query()はfalseを返しています。それがうまくいかない理由です。すべての投稿が表示されています。

<?php 
 
function myCategory($query) { 
 
\t if (! is_admin() && $query->is_main_query() && $query->is_search()) { 
 
\t \t $query->set('category_name', 'friends'); 
 
\t } 
 
} 
 
add_action('pre_get_posts', 'myCategory'); 
 

 

 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
 
$wp_query = new WP_Query('posts_per_page=2&paged='.$paged); 
 
if ($wp_query->have_posts()) { 
 
    \t while ($wp_query->have_posts()) { 
 
\t \t $wp_query->the_post(); 
 
\t \t echo "<h2><a href='".get_the_permalink()."'>".get_the_title()."</a></h2>"; 
 
\t \t the_content("read more..",false); 
 
\t } 
 
} 
 
previous_posts_link("<< Previous"); 
 
next_posts_link("More >>"); 
 

 
?>

しかし、私は次のコードを使用していたときにちょうど$ query-> is_main_queryを(削除する)場合の条件からmyCategory内側(:ここに私のindex.htmlファイル内のコードです)関数で動作しています。

<?php 
 
function myCategory($query) { 
 
\t if ($query->is_home() && ! is_admin()) { 
 
\t \t $query->set('category_name', 'friends'); 
 
\t } 
 
} 
 
add_action('pre_get_posts', 'myCategory'); 
 

 

 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
 
$wp_query = new WP_Query('posts_per_page=2&paged='.$paged); 
 
if ($wp_query->have_posts()) { 
 
    \t while ($wp_query->have_posts()) { 
 
\t \t $wp_query->the_post(); 
 
\t \t echo "<h2><a href='".get_the_permalink()."'>".get_the_title()."</a></h2>"; 
 
\t \t the_content("read more..",false); 
 
\t } 
 
} 
 
previous_posts_link("<< Previous"); 
 
next_posts_link("More >>"); 
 

 
?>

は今、私は$ query-> is_main_query()がfalseを返している理由を知りたいです。だれでも説明できますか?

答えて

0

あなたの例からは、最初のページで検索ページかどうかを確認していて、2番目のページではページがホームになっていることがわかります。だから問題はis_main_query()のチェックではなく、is_search()のもので、おそらくあなたはホームページ上の変更をチェックしているので、それが動作しないのです。