0

I want to modify search.php so that it only shows posts and not pages. Can you help?

Here is the loop in search.php:

<?php if (have_posts()) : ?>
<?php while(have_posts()): the_post(); ?>
1
  • I realized the Avada theme offers this as an option. Not sure if this counts as an answer. However, I may not actively followup on responses to this question for now.
    – nilanjan
    Commented Sep 4, 2013 at 16:03

3 Answers 3

1

The search template is way too late to change anything: The pages are searched already here, and your page numbers would be wrong. Do not alter the output, alter the query.

Filter posts_search instead, and if there is a search term, filter posts_where_paged and remove the post type you don’t want to be searched.

Sample code:

is_admin() || add_filter( 'posts_search', function( $search )
{
    empty ( $search ) || add_filter( 'posts_where_paged', function( $where ) {
        return preg_replace(
            '~post_type IN \((.*)\'page\',?~',
            'post_type IN (\1',
            $where
        );
    });

    return $search;
});
5
  • I am very new to Wordpress. Is this code to be placed in functions.php. Wondering if you want to explain the code, alternatively I can just try to use it
    – nilanjan
    Commented Sep 1, 2013 at 13:40
  • Your code will not work if the user will search blank string .any solution for that ? Commented Aug 24, 2016 at 14:00
  • @PrafullaKumarSahu Yes, there is a separate solution.
    – fuxia
    Commented Aug 24, 2016 at 14:03
  • Thank you so much for your reply and I was already on that page and it seems non of the 3 solutions are working at least for me :( Commented Aug 24, 2016 at 14:13
  • @toscho another problem I am facing with your solution is all newly created pages are comming in search result !!!! Commented Sep 21, 2016 at 13:57
1

I wrote an article on this a while back: Excluding Certain Posts Or Pages From Search Results In WordPress

But the long and short of it is:

function mySearchFilter($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    };
    return $query;
};

add_filter('pre_get_posts','mySearchFilter');

You can add that to your theme's functions.php file.

What it does is filter the main database query WP runs before it actually runs, and tells WP to only look for posts.

0

replace your loop with this and let me know if this work.

<?php if ( have_posts() ) : 
    while ( have_posts() ) : the_post();?>
        <?php if (is_page()) continue; ?>
   <?php endwhile; ?>
 <?php endif; ?>  
1
  • This didn't work. I tried to create another page with my search term and it shows up.
    – nilanjan
    Commented Sep 1, 2013 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.