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。有誰可以解釋一下嗎?