2014-09-22 129 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 
)