【问题标题】:wordpress group by post type on search pagewordpress 在搜索页面上按帖子类型分组
【发布时间】:2011-10-09 18:01:34
【问题描述】:
我想显示按帖子类型分组的搜索结果。我有定期的帖子,页面,
和自定义帖子类型的产品。我将如何通过编辑以下代码来实现这一点。
下面的代码只显示了现在所有的帖子和页面。
<?php
while (have_posts()) : the_post();
echo "<h1>";
echo $post->post_type;
echo $post->post_title;
echo "</h1>";
endwhile;
?>
【问题讨论】:
标签:
wordpress
search
wordpress-theming
【解决方案1】:
此代码会更改原始搜索查询,以按照您选择的顺序按帖子类型对结果进行排序。还有其他解决方案,但这是我发现的唯一一个不会破坏分页或需要多个查询的解决方案。
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;
}
【解决方案2】:
在你的情况下,我会做两件事:
- 将搜索页面的初始查询过滤到特定的帖子类型
- 为每个剩余的帖子类型使用一个
WP_Query 调用
对于 (1),这将进入您的 functions.php:
<?php
function SearchFilter($query) {
if ($query->is_search && !is_admin()) {
if (isset($query->query["post_type"])) {
$query->set('post_type', $query->query["post_type"]);
} else {
$query->set('post_type', 'product');
}
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
?>
对于 (2),修改您从模板文件中提供的代码:
<?php
$s = isset($_GET["s"]) ? $_GET["s"] : "";
$posts = new WP_Query("s=$s&post_type=post");
if ( $posts->have_posts() ) :
while ( $posts->have_posts() ) : $posts->the_post();
echo "<h1>";
echo $post->post_type;
echo $post->post_title;
echo "</h1>";
endwhile;
wp_reset_postdata();
endif;
?>
您可以将此代码重复用于其他帖子类型。
最好避免使用query_posts...参见querying posts without query_posts(即使是 WordPress 开发人员也同意)。