我想显示按帖子类型分组的搜索结果。我有定期的帖子,页面, 和自定义帖子类型的产品。我将如何通过编辑以下代码来完成此操作。 下面的代码现在只显示所有帖子和页面。
<?php
while (have_posts()) : the_post();
echo "<h1>";
echo $post->post_type;
echo $post->post_title;
echo "</h1>";
endwhile;
?>
最佳答案
此代码更改了原始搜索查询,以按照您选择的顺序按帖子类型对结果进行排序。还有其他解决方案,但这是我发现的唯一一个不会破坏分页或需要多个查询的解决方案。
add_filter('posts_orderby', 'my_custom_orderby', 10, 2);
function my_custom_orderby($orderby_statement, $object) {
global $wpdb;
if (!is_search())
return $orderby_statement;
// Disable this filter for future queries (only use this filter for the main query in a search page)
remove_filter(current_filter(), __FUNCTION__);
$orderby_statement = "FIELD(".$wpdb - > prefix.
"posts.post_type, 'post-type-c', 'post-type-example-a', 'custom-post-type-b') ASC";
return $orderby_statement;
}
关于wordpress 在搜索页面上按帖子类型分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6768409/