wordpress group by post type在搜索页面上

时间:2011-07-20 20:53:20

标签: wordpress search wordpress-theming

我想显示按帖子类型分组的搜索结果。我有常规帖子,页面, 和自定义的帖子类型的产品。如何通过编辑以下代码来实现这一目标。 下面的代码现在只显示所有帖子和页面。

<?php
 while (have_posts()) : the_post();  
 echo "<h1>";
 echo $post->post_type;
 echo $post->post_title;
 echo "</h1>";
 endwhile;
 ?>

3 个答案:

答案 0 :(得分:4)

此代码会更改原始搜索查询,以按您选择的顺序按类型对结果进行排序。还有其他解决方案,但这是我发现的唯一一个不会破坏分页或需要多个查询的解决方案。

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;
}

答案 1 :(得分:2)

在你的情况下,我会做两件事:

  1. 将搜索页面的初始查询过滤为特定的帖子类型
  2. 对每个剩余的帖子类型使用WP_Query次调用
  3. 对于(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开发者也同意)。

答案 2 :(得分:-1)

您需要更改帖子查询以重新排序内容。您可以在进入循环之前执行此操作。您可以在Wordpress codex中阅读有关query_posts的更多信息。

http://codex.wordpress.org/Function_Reference/query_posts

global $wp_query;
$args = array_merge( $wp_query->query, array( 'post_type' => array('type1', 'type2') ) );
query_posts( $args );
//the loop