如果我有自定义帖子类型 (post_type
),并且我想保证帖子类型为 product
的任何内容都出现在搜索结果中的其他任何内容之前,那么如何我能实现这个目标吗?最好只更改查询的 order by
部分。
目前我有:
ORDER BY posts.post_type DESC, posts.post_date DESC
此方法有效,但在 DESC
上,另一种类型的 testimonial
出现在 product
之前。在 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;
}
最佳答案
您可以在 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
理想情况下,我会将产品类型转移到另一个表,并为每种类型指定一个优先级整数。这样您就可以完全控制顺序,而不会发生这样的戏剧性事件!
关于MYSQL 按查询顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25983840/