我目前使用以下代码列出Archive.php中的帖子,但我希望结果按名称按升序排列,我已经检查了编解码器,但答案对我来说还不清楚,如何使它正常工作? br />
<?php $post = $posts[0]; // ?>


谢谢。

评论

如果您在archive.php中使用自定义查询,可以显示它吗?可能会将完整的archive.php发布在pastie.org上,并使用链接更新您的答案?

#1 楼

最简单的方法是使用挂钩(pre_get_posts挂钩)来更改顺序。但是您应该检查查询是否确实要更改其顺序! (is_archive()is_post_type_archive()应该足够。)例如,将以下内容放入主题的函数中。php...

add_action( 'pre_get_posts', 'my_change_sort_order'); 
    function my_change_sort_order($query){
        if(is_archive()):
         //If you wanted it for the archive of a custom post type use: is_post_type_archive( $post_type )
           //Set the order ASC or DESC
           $query->set( 'order', 'ASC' );
           //Set the orderby
           $query->set( 'orderby', 'title' );
        endif;    
    };


评论


您好,您将能够显示默认排序的工作方式吗?一些链接,如果可能的话。谢谢

– Latheesh V M Villa
19年9月7日在21:34

@LatheeshVMVilla WP是作为博客开发的,因此明智的/默认的排序是通过post_date DESC(= descending)进行的,因此这是最新的,后继的。如果您将WP用于时间不重要的事物(大多数列表类型,例如记录集合,食谱,词汇表等),则需要经常订购post_title ASC(=升序,因此按字母顺序前面有数字)。

–user3445853
19/12/3在13:25

谢谢。适用于我的分类存档页面。

– SemaHernández
20年5月5日在16:12

工作完美。谢谢!

– Mark P
20年6月17日在18:59

#2 楼

<?php
// we add this, to show all posts in our
// Glossary sorted alphabetically
if ( is_category('Glossary') )  {
    $args = array( 
        'posts_per_page' => -1, 
        'orderby'        => 'title', 
        'order'          => 'ASC' 
    );
    $glossaryposts = get_posts( $args );
}
foreach( $glossaryposts as $post ) : setup_postdata( $post );
    ?>
    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>


评论


您能解释一下为什么这对OP有帮助吗?请始终在一段代码的顶部添加说明。谢谢。

– kaiser
17年1月20日在23:12

问题是在Archive.php上按名称和升序对结果进行排序。大概根据回答者,此代码将按Archive.php上的名称和升序对结果进行排序?

–乔恩
19/12/11在14:37

#3 楼

进一步回答斯蒂芬的问题,如果您只想按标题查询和排序,则可以在模板文件中使用它:

评论


直接来自WordPress代码参考-“此功能将完全覆盖主查询,并且不打算由插件或主题使用。它过于简单的修改主查询的方法可能会出现问题,应尽可能避免。在这种情况下,可以使用更好,更高性能的选项来修改主查询,例如通过WP_Query中的“ pre_get_posts”操作。”底线@Stephen Harris拥有完成此任务的正确方法。 developer.wordpress.org/reference/functions/query_posts

–迈克尔
16-10-13在14:33