在WordPress中按字母顺序对帖子进行排序


Sorting posts alphabetically in WordPress

使用WordPress Codex中的这些信息,我尝试在WordPress中按字母顺序对帖子进行排序,现在正在处理搜索结果。

这是模板中的默认代码,适用于搜索,但默认情况下会按时间顺序颠倒排列:

<?php while ( have_posts() ) : the_post(); ?>
    <?php get_template_part( 'content', apptheme_get_list_type() ); ?>
<?php endwhile; ?>

现在,我尝试将其更改为:

<?php
    while ( have_posts() ) : the_post();
        $args = array( 'posts_per_page' => -1, 'orderby'=> 'title', 'order' => 'ASC' );
        $sorted_posts = get_posts( $args );
    endwhile;
?>
<?php foreach ($sorted_posts as $post): setup_postdata($post); ?>
    <?php get_template_part( 'content', apptheme_get_list_type() ); ?>
<?php endforeach; ?>

这适用于排序顺序,但它会返回所有帖子,而不仅仅是适合搜索的帖子。我应该更改什么参数?(我熟悉PHP,但这是我第一次修改WordPress模板)

谢谢!

我没有尝试过,但它应该可以工作:

add_filter('posts_orderby','custom_search_sort_custom',10,2);
function custom_search_sort_custom( $orderby, $query ){
    global $wpdb;
    if(is_search()) 
        $orderby =  $wpdb->prefix."posts.post_type ASC, {$wpdb->prefix}posts.post_title ASC";
    return  $orderby;
}