为什么 is_main_query() inside pre_get_posts hook 在主循环中不返回 true?

Why isn't is_main_query() inside pre_get_posts hook returning true while inside the main loop?

我的主题中有一个 index.php 模板,带有一个简单的 while 循环来显示帖子,如下所示:

<section class="c-section overflow-hidden pt-0">
<div class="o-wrapper">
<?php
if ( have_posts() ) : $i=0;
?>
        <div class="row col-gutters pt-6">
            <?php while ( have_posts() ) : the_post(); ?>
                <div class="col-md-6 mb-3">
                <?php $thumb_id = get_post_thumbnail_id();
                $cardDate = get_the_date();
                $cardTitle = get_the_title();
                $cardExcerpt = get_excerpt();
                $cardLink = get_the_permalink();
                $cardExternal = get_field('external_article');
                $cardExternalLink = get_field('external_article_link');
                $cardExternalSource = get_field('external_article_source');
                    include(locate_template('_components/card-newsroom.php'));
                $i++;?>
                </div>
        <?php endwhile;?>
    </div>
  <?php endif;?>
</div>
</section>

我正在尝试使用 functions.php 中的 pre_get_posts 来修改显示的帖子数量,并删除特定类型的帖子。

function remove_news_posts( $query ) {
if ( $query->is_main_query() && !is_front_page() && !is_page() && !is_page_template() && !is_search() && !is_feed() && !is_tax() && !is_admin()) :

  $query->set( 'meta_query', array(
    'relation' => 'AND',
    array(
      'key' => 'external_article',
      'value' => 0,
      'compare' => 'LIKE',
    )
  ));

  $query->set( 'posts_per_page', '6');
}

add_action( 'pre_get_posts', 'remove_news_posts', 1000 );

但是 - 这不起作用。每页的帖子不是 6,元查询也不影响显示的帖子。我有一个几乎相同的 category.php 模板,并且 pre_get_posts() 过滤器在那里工作。如果我从 pre_get_posts if 语句中删除 $query->is_main_query(),它工作正常。但是它也会影响我不希望受到影响的其他查询(比如在侧边栏中)。

为什么 is_main_query() return 不是真的,而我期望 return 是真的?

因为在你的声明中检查是否不在首页!

您可以替换为:

if ( $query->is_main_query() && (is_home() || is_archive())){ ....

我终于明白了!发生了两件事:

  1. 模板层次结构。我的 index.php 文件应该是 home.php,帖子索引页面的正确模板。看这里:https://developer.wordpress.org/themes/basics/template-hierarchy/
  2. 过滤系统正在使用 query_posts(),这也修改了主查询。根据官方 WordPress 文档,不推荐使用 query_posts():"This function will completely override the main query and isn’t intended for use by plugins or themes. Its overly-simplistic approach to modifying the main query can be problematic and should be avoided wherever possible."(参见 https://developer.wordpress.org/reference/functions/query_posts/

希望这对外面的人有所帮助。干杯!