WordPress通过标准循环更改帖子的顺序


Wordpress change the order of posts through the standard loop

是否可以在保持标准Wordpress循环不变的同时对帖子进行排序(即无需创建全新的WP_Query?

通过标准循环,我的意思是:

<?php if ( have_posts() ) : ?>

            <?php /* The loop */ ?>
            <?php while ( have_posts() ) : the_post(); ?>

我可以在此代码中指定顺序吗?

query_posts函数页面所述:

强烈建议您使用pre_get_posts过滤器 相反,并通过选中 is_main_query 来更改主查询。

您可以对模functions.php文件中的pre_get_posts添加新操作,例如:

function homepage_posts($query)
{
    if ($query->is_home() && $query->is_main_query())
    {
        $query->set( 'orderby', 'title' );
    }
}
add_action('pre_get_posts', 'homepage_posts');

> wp_reset_query() 是要走的路

示例代码段

<?php query_posts(array('orderby'=>'title','order'=>'DESC'));
if ( have_posts() ) :
    while ( have_posts() ) : the_post(); ?>
        <a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
    endwhile;
endif;
wp_reset_query();

但请记住:query_posts() 会更改您的主查询,不建议这样做。仅在绝对必要时使用(见query_posts:注意事项)。创建 WP_Query 或 get_posts() 的新实例是辅助循环的首选。