2016-09-28 59 views
3

我在wordpress myTheme文件夾中有一個非常簡單的index.php文件,我只想使用'pre_get_posts'鉤子顯示帶有「friends」類別的帖子。但if條件中的$ query-> is_main_query()返回false。這就是爲什麼它沒有工作,它顯示了所有的帖子。這裏是我的index.html文件中的代碼:)從如果條件myCategory內

<?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 >>"); 
 

 
?>

但是,當我使用下面的代碼只刪除了$查詢 - > is_main_query(( )功能,它的工作。

<?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 >>"); 
 

 
?>

現在,我想知道爲什麼$查詢 - > is_main_query()的返回false。有誰可以解釋一下嗎?

回答

0

從你的例子中我看到,第一個你檢查它是否是一個搜索頁面,第二個是你正在檢查的頁面是否在家。所以我會說問題不在於is_main_query()檢查,而在於is_search(),可能是檢查主頁上的更改,這就是爲什麼它不起作用。

相關問題