Maarten Wolfsen
Maarten Wolfsen

Reputation: 1733

Filter WordPress search results between different (custom) post types

I have an search.php file, which shows the search results of the user's search, using this code:

<?php
$s=get_search_query();
$args = array('s' =>$s);

$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) { ?>

  <?php while ( $the_query->have_posts() ) {
    $the_query->the_post();
     ?>
      <h1><?php the_title(); ?></h1>
  <?php } 

}else{ ?>
  <h1>No search results found</h1>
<?php } 

?>

Is there a way, where I can filter the results between different (custom) post types?

Like this:

- item1 (post)
- item2 (custom post type named 'clients')
- item3 (custom post type named 'clients')
- item4 (custom post type named 'occasions')
- item5 (post)

Upvotes: 1

Views: 127

Answers (1)

Pierre
Pierre

Reputation: 847

You just need to display the post post_type in your loop :

<h1><?php the_title(); ?> (<?php echo get_post_type(); ?>)</h1>

And ideally, you should add wp_reset_postdata(); after the closing of while loop, to keep clean the bottom of your page :

<?php while( $the_query->have_posts() ){
    $the_query->the_post(); ?>
    <h1><?php the_title(); ?> (<?php echo get_post_type(); ?>)</h1>
<?php } 
wp_reset_postdata();

Upvotes: 2

Related Questions