Archive.php 不对单个类别的帖子进行排序

Archive.php isn't sorting posts from one single category

我添加了数字分页的存档页面不会整理出正确的类别,而是显示所有类别的 posts。假设类别是香蕉 (http:///localhost/tkeblog/category/bananas/),我从类别香蕉、橙子和苹果中得到 post。此外,分页系统不显示带有缩略图的 posts,但它在我的 index.php 页面上有效。我在按类别过滤 post 时做错了什么?

<?php
if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }

query_posts(array(
    'post_type'      => 'post', // You can add a custom post type if you like
    'paged'          => $paged,
    'posts_per_page' => 5
));

if ( have_posts() ) : the_post(); ?>
<div class="blogitem a">


<?php while ( have_posts() ) : the_post(); ?>

    <?php get_template_part('catalog',get_post_format()); ?>

<?php endwhile; ?>

<div class="pagination">
    <?php my_pagination(); ?>
    </div>

</div>
 <?php else: ?>
<p>Sorry, no posts matched your criteria.</p>
 
<?php wp_reset_query(); ?>

<?php endif; ?>

如果我们看一下默认的 TwentyTwentyOne Wordpress theme archive.php,我们可以看到存档模板只是使用默认循环来显示所有类别的所有帖子,而不是自定义查询。

我相信这回答了你的问题。

<?php
if( have_posts() ):
  while( have_posts() ): the_post();
    // ... template
  endwhile;
else:
    // ... fallback
endif; ?>

如果您想从 archive.php 页面自定义默认查询输出,最佳做法是从您的 function.php 页面进行。您可以使用动作挂钩过滤器 pre_get_posts.

Fires after the query variable object is created, but before the actual query is run. Be aware of the queries you are changing when using the pre_get_posts action. Make use of conditional tags to target the right query.

<?php
add_action( 'pre_get_posts', function ( $query ) {
  if ( ! is_admin() && $query->is_archive() && $query->is_main_query() ) {
    if ( get_query_var( 'post_type' ) == 'post' ) {
      $query->set( 'post_type', array( 'post' ) );
      $query->set( 'posts_per_page', 12 );
      $query->set( 'orderby', array( 'date' ) );
      $query->set( 'order', array( 'ASC' ) );
    } else {
      $query->set( 'posts_per_page', 6 );
      $query->set( 'orderby', array( 'date' ) );
      $query->set( 'order', array( 'ASC' ) );
    };
  };
}; ?>