wordpress按搜索页面上的帖子类型分组
我想显示按帖子类型分组的搜索结果。我有固定的帖子,页面, 和一个定制的post类型的产品。我将如何通过编辑下面的代码来实现这一点。 下面的代码只显示了现在所有的文章和页面wordpress按搜索页面上的帖子类型分组,wordpress,search,wordpress-theming,Wordpress,Search,Wordpress Theming,我想显示按帖子类型分组的搜索结果。我有固定的帖子,页面, 和一个定制的post类型的产品。我将如何通过编辑下面的代码来实现这一点。 下面的代码只显示了现在所有的文章和页面 <?php while (have_posts()) : the_post(); echo "<h1>"; echo $post->post_type; echo $post->post_title; echo "</h1>"; endwhile; ?> 您需
<?php
while (have_posts()) : the_post();
echo "<h1>";
echo $post->post_type;
echo $post->post_title;
echo "</h1>";
endwhile;
?>
您需要更改post查询以重新排序。您将在进入循环之前执行此操作。你可以在Wordpress codex中阅读更多关于查询的文章
在你的情况下,我会做两件事:
<?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;
?>
您可以对其他帖子类型重复使用此代码
最好避免使用。。。请参阅(即使WordPress开发人员同意)。此代码更改原始搜索查询,以按您选择的顺序按帖子类型排序结果。还有其他解决方案,但这是我发现的唯一一个不中断分页或需要多个查询的解决方案
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;
}
如果你的方法不错,但值得一提的是,你的答案不尊重分页。
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;
}