首页 > 解决方案 > 按时间(升序)顺序显示 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();
    ?>

我认为这会很简单,尽管我发现尝试的所有东西也无法正常工作。谢谢!

标签: phpwordpressloops

解决方案


使用自定义循环:

如果您正在创建一个自定义循环,您可能想要使用它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' );

我建议使用过滤器路径以避免更改大量当前模板。


推荐阅读