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(); ?>
  • 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 Sep 4 '13 at 16:03

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',

    return $search;
  • 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 Sep 1 '13 at 13:40
  • Your code will not work if the user will search blank string .any solution for that ? – Prafulla Kumar Sahu Aug 24 '16 at 14:00
  • @PrafullaKumarSahu Yes, there is a separate solution. – fuxia Aug 24 '16 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 :( – Prafulla Kumar Sahu Aug 24 '16 at 14:13
  • @toscho another problem I am facing with your solution is all newly created pages are comming in search result !!!! – Prafulla Kumar Sahu Sep 21 '16 at 13:57

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;


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.


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; ?>  
  • This didn't work. I tried to create another page with my search term and it shows up. – nilanjan Sep 1 '13 at 13:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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