Search results sorted by post types

I am working on a site with several post types – 4 to be exact – and I am trying to setup the search results page to have a filter/sort the results by post types.

For example, when a person searches a term they are taking to the page with the results, all posts found from all post types are shown but up top there are the different post types name links that will sort the results and show only the respective post type’s post. Right now I have several loops on the search results page for each post type but when I test it, the loops are all showing the same results even though each loop has a query for a different post type.

Read More

How do I fix the loop so that it only shows the search results from that post type? I dont want to have different search forms or reset the query and end up losing the search term. Here is some of the code from the page — http://pastebin.com/L9zEw1cn

The first loop is the default loop which will show all the results and the second loop is the loop I am trying to use for the rest of the post types.

So is there anyway to fix the second loop so that it only shows the search results for that post type?

Any help would be greatly appreciated. Thanks.

Reply

Related posts

Leave a Reply

2 comments

  1. You can use filter posts_clauses
    For example:

    add_filter( 'posts_clauses', 'post_query_order', 20, 1 );
    function post_query_order( $pieces )
    {
        global $wpdb;
        $pieces['orderby'] = $wpdb->prefix.'posts.post_type ASC';
        return $pieces;
    }
    
  2. In your second loop you are setting up arguments for posts query but you are not using them anywhere. You should place query_posts( $args ) before the second loop. You could also use a get_posts function or WP_Query class.

    EDIT: From page about query_posts function on WordPress codex:

    query_posts() is the easiest, but not preferred or most efficient, way to alter the default query that WordPress uses to display posts. Use query_posts() to display different posts than those that would normally show up at a specific URL.

    Right now, in your code, you are looping twice through the same posts. The second loop is exactly the same as the first one.

    Now, if you place query_posts() with different arguments before the second loop, like this:

    $args = array( 'post_type' => 'videos', 's' => $s );
    query_posts( $args );
    if(have_posts()) :
    while(have_posts()) :
    the_post();
    
    // Display the post
    
    endwhile; endif;
    wp_reset_postdata(); ?>

    You will be looping through different set of posts.