php - Archive.php 没有对单个类别的帖子进行排序
问题描述
我添加了数字分页的存档页面不会整理出正确的类别,而是显示所有类别的帖子。假设类别是香蕉 (http://localhost/tkeblog/category/bananas/),我从香蕉、橙子和苹果类别中获得帖子。此外,分页系统不会显示带有缩略图的帖子,但它可以在我的 index.php 页面上运行。我在按类别过滤帖子时做错了什么?
<?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 主题archive.php
,我们可以看到归档模板只是使用默认循环来显示所有类别的所有帖子,而不是自定义查询。
我相信这回答了你的问题。
<?php
if( have_posts() ):
while( have_posts() ): the_post();
// ... template
endwhile;
else:
// ... fallback
endif; ?>
如果您想自定义页面的默认查询输出,最佳实践是从archive.php
您的function.php
页面进行。您可以使用动作挂钩过滤器pre_get_posts
。
在创建查询变量对象之后但在实际查询运行之前触发。请注意您在使用 pre_get_posts 操作时更改的查询。利用条件标签来定位正确的查询。
<?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' ) );
};
};
}; ?>
推荐阅读
- python - 基于 3D 数组 numpy 创建 2D 数组
- email - Jenkins Ext 电子邮件显示地址尚未配置 - 即使在设置系统管理员电子邮件之后
- javascript - 如何将优惠券添加到条纹结帐
- c# - 从正文接收 JSON 并对其进行迭代
- microsoft-graph-api - 带有 HTTP 状态 200 响应的 Microsoft Graph 的 One Drive 内容 API
- websocket - 在 Julia 中使用 Websocket 时遇到问题
- java - 为什么 Apache 项目对 Java 版本敏感?
- javascript - 当改变一个模块对象时,为什么花括号导入没有改变?
- android - MediaFilePicker 总是显示空目录
- r - 在ggplot上绘制连接两点的线段