Skip to content

Instantly share code, notes, and snippets.

@evagoras
Last active September 28, 2023 16:22
Show Gist options
  • Select an option

  • Save evagoras/7e84da635af6adc7cdfce7f75e38754e to your computer and use it in GitHub Desktop.

Select an option

Save evagoras/7e84da635af6adc7cdfce7f75e38754e to your computer and use it in GitHub Desktop.
How to handle and customize an empty search query in WordPress
http://www.mysamplesite.com/?s=
function SearchFilter($query) {
// If 's' request variable is set but empty
if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){
$query->is_search = true;
$query->is_home = false;
}
return $query;
}
add_filter('pre_get_posts','SearchFilter');
<?php get_header(); ?>
<div class="container">
<div class="row">
<div class="span12">
<?php if ( have_posts() && strlen( trim(get_search_query()) ) != 0 ) : ?>
<div class="page-header">
<h1 class="page-title">
Search Results for
<small><?php echo get_search_query(); ?></small>
</h1>
</div>
<?php while ( have_posts() ) : the_post(); ?>
<div class="row-fluid">
<?php if ( has_post_thumbnail() ) : ?>
<div class="span3">
<a
class="thumbnail"
title="<?php the_title_attribute(); ?>"
href="<?php the_permalink(); ?>"
>
<?php the_post_thumbnail( 'medium' ); ?>
</a>
</div><!--/.span3 -->
<div class="span9">
<?php else : ?>
<div class="span12">
<?php endif; ?>
<h3>
<a title="<?php the_title();?>" href="<?php the_permalink(); ?>">
<?php the_title(); ?>
</a>
</h3>
<?php the_excerpt();>
</div><!-- /.row-fluid -->
<hr />
<?php endwhile; ?>
<?php else : ?>
<div class="page-header">
<h1 class="page-title">No results Found</h1>
<p>
It seems we can’t find what you’re looking for.
Perhaps you should try again with a different search term.
</p>
</div>
<div class="well">
<?php get_search_form(); ?>
</div><!--/.well -->
<?php endif ;?>
<?php paging_content_nav( 'nav-below' ); ?>
</div><!--/.span8 -->
</div><!--/.row -->
</div><!--/.container -->
<?php get_footer(); ?>
@evagoras

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment