2016-03-16 35 views
0

使用WordPress Codex中的this information我嘗試在WordPress中按字母順序排列帖子,現在正在處理搜索結果。在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模板)

謝謝!

+0

' 'posts_per_page'=> -1'給你所有的帖子後面。只需在那裏定義一個數字,你只能得到這個數字。 – staypuftman

+0

查詢參數的完整列表可以在這裏找到:https://codex.wordpress.org/Class_Reference/WP_Query – staypuftman

+0

寫在該codex頁面上的大部分內容只是很多廢話。可悲的是,這不是代碼中唯一完全廢話的頁面。回到你的主/原始循環。您不應該運行自定義查詢來代替主查詢。一旦你回到** all *頁面的主循環,使用'pre_get_posts'來修改主查詢來滿足你的需求 –

回答

0

我還沒有試過,但它應該工作:

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; 
}