WordPress Search Results Page Modifications

Below is a list of code snippets that may help you out when creating your WordPress Search Results Page.

Removing Pagination on WordPress Search Results

Search results incorporate your default wordpress pagination settings, you can change the pagination limit on the search results without having to adjust the wordpress query. To do this you need to hook into the search query and change the posts_per_page limit.

 * Unlimited Search Posts
function jc_limit_search_posts() {
	if ( is_search())
		set_query_var('posts_per_page', -1);
add_filter('pre_get_posts', 'jc_limit_search_posts');

WordPress Search redirecting to Homepage

By default if a search is submitted, if no keyword is present instead of going to the search results page you will be redirected to the homepage. To fix this you can automatically populate the search $_GET request with an empty space:

 * Stop Empty Search Requests redirecting to homepage
function jc_stop_search_redirect( $vars ) {
	if( isset( $_GET['s'] ) && empty( $_GET['s'] ) )
		$vars['s'] = " ";
	 return $vars;
add_filter( 'request', 'jc_stop_search_redirect' );

Filter WordPress Search Results

Wanting to stop certain pages or posts being displayed in your search results?, this example hooks into the pre_get_posts filter and specifies to only search pages and posts that do not have ID’s 25,27,…

 * Example showing how to limit search results to pages and posts, and not allowing specific posts/pages
function jc_filter_search_results($query) {
	// check to see if search
	if ($query->is_search) {
		// only search the paeg post type
		$query->set('post_type', array('page', 'post'));
		// dont search these pages
		$query->set('post__not_in', array(25,27,29,31,33,291));
	return $query;

WordPress Search Results Template Page

To customise the search results template create a new file in the theme called search.php, this will only be used on the search page.

 * Search Results Template File
get_header(); ?>
		<h1>Search Results: &quot;<?php echo get_search_query(); ?>&quot;</h1>
<?php if ( have_posts() ) :  // results found?>
	<?php while ( have_posts() ) : the_post(); ?>
			<h2><?php the_title();  ?></h2>
			<p><?php the_excerpt(); ?></p>
			<p> <a href="<?php the_permalink(); ?>">View</a> </p>
	<?php endwhile; ?>
<?php else :  // no results?>
		<h1>No Results Found.</h1>
<?php endif; ?>
<?php get_footer(); ?>

Liked this article? help spread the word.