2014-09-22 128 views
0

如果我有自定義帖子類型(post_type),並且我想保證任何帖子類型爲product的帖子出現在搜索結果中的其他任何內容之前,我怎麼能實現這一點?最好通過改變查詢的部分order by通過查詢MYSQL訂單

目前我有:

ORDER BY posts.post_type DESC, posts.post_date DESC 

這工作,但另一篇文章類型testimonialproductDESC之前。在ASC不同的自定義帖子類型articles之前product但我需要product先來(與他們訂購post_date),然後一切 - 也排序post_date

的完整代碼:

add_filter('posts_orderby','search_sort_custom',10,2); 
function search_sort_custom($orderby, $query) 
{ 
    global $wpdb; 

    if(!is_admin() && is_search()) { 
     $orderby = $wpdb->prefix."posts.post_type DESC, {$wpdb->prefix}posts.post_date DESC"; 

    } 
    return $orderby; 
} 

回答

1

您可以在ORDER BY子句中使用表達式:

ORDER BY posts.post_type='product' DESC, 
     posts.post_type DESC, 
     posts.post_date DESC 

如果您有更多的需求,你可以這樣做:

ORDER BY posts.post_type='product' DESC, 
     posts.post_type='testimonial' DESC, 
     posts.post_type DESC, 
     posts.post_date DESC 

或使用FIND_IN_SET

ORDER BY FIND_IN_SET(posts.post_type,'product, testimonial'), 
     posts.post_type DESC, 
     posts.post_date DESC 

然而,理想情況下,我會將產品類型轉移到另一個表中,併爲每種類型賦予一個優先級整數。這種方式可以完全控制沒有這種戲劇的訂單!

+0

謝謝,我能做到! post_type = '產品' DESC, posts.post_type = '產品' DESC, posts.post_date DESC – Martin 2014-09-22 22:23:51

+0

抱歉,您仍然是保持分組的舊錶達式。請參閱更新。比較結果返回1或0(真/假),所以你的建議與我原來的一樣。 – Arth 2014-09-22 22:32:25

+0

Thanks Arth ...因此,這將返回由post_date DESC首先訂購的所有產品,以及由post_date DESC訂購的所有其他產品(混合在一起)。如果是這樣,真棒,因爲這是我所追求的。 – Martin 2014-09-22 22:46:46

0

你可以簡單地只是做

ORDER BY (
    posts.post_type = 'product' DESC, 
    posts.post_type DESC, 
    posts.post_date DESC 
)