How to control WordPress Search Behavior?

What you tried to use is broken.

add_filter( 'pre_get_posts', 'modified_pre_get_posts' ); 
function modified_pre_get_posts( WP_Query $query ) { 
  if ( $query->is_search() ) { 
    $query->set( 'post_type', array( 'page-home' ) ); 
  } 
  return $query; 
}

That function definition is not valid. You would have seen an error if you had debugging enabled. You need:

add_filter( 'pre_get_posts', 'modified_pre_get_posts' ); 
function modified_pre_get_posts( $query ) { 
  if ( $query->is_search() ) { 
    $query->set( 'post_type', array( 'page-home' ) ); 
  } 
  return $query; 
}

But that will only search for post_type = “page-home”. I don’t think that is correct either. I assume that is how you’d hoped to exclude the home page. In fact you did something very different. I think you want:

add_filter( 'pre_get_posts', 'modified_pre_get_posts' ); 
function modified_pre_get_posts( $query ) { 
  if ( $query->is_search() ) { 
    $query->set( 'post__not_in', array( id-of-home-page ) ); // should be a number; you have to replace that text with the actual ID
  } 
  return $query; 
}

With the default search widget, on my beaten and abused sandbox install, no search runs if I try to submit without any terms. The blog index page loads. If you want to completely interrupt the submission, though, you will need to do it with Javascript.

Leave a Comment