WordPress search results multiple loops

The following is my search.php:

<?php if (have_posts()) : ?>
    <h2 class="pagetitle">Page Search Results</h2>
    <?php while (have_posts()) : the_post(); ?>
        <?php if ($post->post_type == 'page') : ?>
             Show Page results
        <?php endif; ?>
    <?php endwhile; ?>

    <?php rewind_posts(); ?>
    <h2 class="pagetitle">Post Search Results</h2>
    <?php while (have_posts()) : the_post(); ?>
        <?php if ($post->post_type != 'page') : ?>
             Show non-page results
        <?php endif; ?>
    <?php endwhile; ?>

<?php else : ?>
 No Results
<?php endif; ?>

The code allows search results under posts to be separated from those found in pages. If no search results are found for either posts or pages, the text “No Results” is displayed.

Read More

However, when results are found for pages but NOT posts (and vice versa), under the ‘Post Search Results” there is nothing displayed. I would like the code tweaked so that if there are no results found under “Post Search Results” but there are results found under “Page Search Results,” the text “No Results” is displayed underneath the “Post Search Results” header.

Thanks a lot everyone.

Related posts

Leave a Reply

1 comment

  1. Give this a try, you can expand the array to include any post_type your site is using:

    <?php
        foreach (array('post','page') as $pt) :
            $search_query = new WP_Query(array(
                    'post_type'         => $pt,
                    's'                 => $s,
                    'posts_per_page'    => 10,
                    'paged'             => $paged
                )
            );
        ?>
        <?php if ($pt == 'post') : ?>
            <h2 class="pagetitle">Post Search Results</h2>
        <?php else : ?>
            <h2 class="pagetitle">Page Search Results</h2>
        <?php endif; ?>
        <?php 
            if ($search_query->have_posts()) : while ($search_query->have_posts()) : $search_query->the_post();
            if ($pt == 'post') :
        ?>
            Post Results Code
        <?php else : ?>
            Page Results Code
        <?php endif; ?>
        <?php endwhile; else : ?>
            No Results
        <?php endif; ?>
    <?php endforeach; ?>