wordpress 在搜索页面上按帖子类型分组

标签 wordpress search wordpress-theming

我想显示按帖子类型分组的搜索结果。我有定期的帖子,页面, 和自定义帖子类型的产品。我将如何通过编辑以下代码来完成此操作。 下面的代码现在只显示所有帖子和页面。

<?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/

相关文章:

wordpress - apply_filters(...) 在 WordPress 中实际上做了什么?

c++ - 列表类型的binary_search函数的时间复杂度是多少

php - 如何在 wordpress 中为多个 meta_key 更新用户元数据

wordpress-theming - 如何从 Genesis Framework 中删除 'by [author]'

sql - Stack Overflow 相关问题 算法

wordpress - 如何删除自定义帖子类型 url 中的 slug?

javascript - 如何调整 flexslider 的大小?

wordpress - 无法禁用图层动画 - Revolution Slider

php - Woocommerce 优惠券四舍五入问题

go - ldap搜索过滤器以检查特定域下是否存在任何用户