php - 按时间(升序)顺序显示 Wordpress 帖子
问题描述
默认情况下,Wordpress 按时间倒序显示所有帖子(最新帖子在前)。
我想按时间顺序显示我所有的 wordpress 帖子(最旧的帖子首先显示)。
我正在尝试使用自定义循环查询来执行此操作,但是我无法使其正常工作。我在这里想念什么?
<?php query_posts(array('orderby'=>'date','order'=>'ASC'));
if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
<div class="postTitle"><?php the_title(); ?></div>
<div class="postContent"><?php the_content(); ?></div>
<?php endwhile; endif;
wp_reset_query();
?>
我认为这会很简单,尽管我发现尝试的所有东西也无法正常工作。谢谢!
解决方案
使用自定义循环:
如果您正在创建一个自定义循环,您可能想要使用它WP_Query
。
<?php
$the_query = new WP_Query([
'order'=>'ASC'
]);
// The Loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) :
?>
<div class="postTitle"><?php the_title(); ?></div>
<div class="postContent"><?php the_content(); ?></div>
<?php
endwhile;
/* Restore original Post Data */
wp_reset_postdata();
?>
<?php else: ?>
// no posts found
<?php endif; ?>
使用过滤器
或者另一种方法是使用文件中的过滤器更改主循环functions.php
。
function alter_order_of_posts( $query ) {
if ( $query->is_main_query() ) {
$query->set( 'order', 'ASC' );
}
}
add_action( 'pre_get_posts', 'alter_order_of_posts' );
我建议使用过滤器路径以避免更改大量当前模板。
推荐阅读
- html - 打印时设置默认比例
- angular - Angular 2 在表单中添加动态字段并将数据保存到数据库
- reactjs - 在反应 jsx 元素数组值中添加新行
- ios - 在没有 ssl 证书的 WebView 中打开 Https URL
- ios - Appium 测试甚至没有在 AWS DeviceFarm 上开始
- typescript - Typescript 'keyof' 关键字在使用 react setState 函数时出错
- ios - 从 NSObject 类创建一个数组
- visual-studio - Azure DevOps/VSTS 数据库和生产错误修复
- openfire - 使用 smack#UserSearchManager 无法搜索用户
- c# - Unity是触发器和弹丸删除游戏