16

The default search function if the search form is empty returns the home page, I want it to return a "sorry your search returned no results" page.

this post doesn't answer it

and this ticket tells me that it is supposed to function that way! Anyone figure out how to change it besides using a .htaccess redirect?

I'm using the following search.php file: `

        <div id="content" class="clearfix">

            <div id="main" class="col700 left clearfix" role="main">

                <h1 class="archive_title"><span>Search Results for:</span> <?php echo esc_attr(get_search_query()); ?></h1>

                <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

                <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?>>

                    <header>

                        <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>

                        <p class="meta"><?php _e("Posted", "bonestheme"); ?> <time datetime="<?php echo the_time('Y-m-j'); ?>" pubdate><?php the_time('F jS, Y'); ?></time> <?php _e("by", "bonestheme"); ?> <?php the_author_posts_link(); ?> <span class="amp">&</span> <?php _e("filed under", "bonestheme"); ?> <?php the_category(', '); ?>.</p>

                    </header> <!-- end article header -->

                    <section class="post_content">
                        <?php the_excerpt('<span class="read-more">Read more on "'.the_title('', '', false).'" &raquo;</span>'); ?>

                    </section> <!-- end article section -->

                    <footer>


                    </footer> <!-- end article footer -->

                </article> <!-- end article -->

                <?php endwhile; ?>  

                <?php if (function_exists('page_navi')) { // if expirimental feature is active ?>

                    <?php page_navi(); // use the page navi function ?>

                <?php } else { // if it is disabled, display regular wp prev & next links ?>
                    <nav class="wp-prev-next">
                        <ul class="clearfix">
                            <li class="prev-link"><?php next_posts_link(_e('&laquo; Older Entries', "bonestheme")) ?></li>
                            <li class="next-link"><?php previous_posts_link(_e('Newer Entries &raquo;', "bonestheme")) ?></li>
                        </ul>
                    </nav>
                <?php } ?>          

                <?php else : ?>

                <!-- this area shows up if there are no results -->

                <article id="post-not-found">
                    <header>
                        <h1>No Results Found</h1>
                    </header>
                    <section class="post_content">
                        <p>Sorry, but the requested resource was not found on this site.</p>
                    </section>
                    <footer>
                    </footer>
                </article>

                <?php endif; ?>

            </div> <!-- end #main -->

            <div id="sidebar1" class="sidebar right col220">

                <?php get_search_form(); ?>



            </div>

        </div> <!-- end #content -->

`

9
  • show some code?
    – kaiser
    Commented Sep 26, 2011 at 15:18
  • I don't even know where to start to address this (besides the htaccess), so no code. Any help is appreciated
    – Drai
    Commented Sep 26, 2011 at 16:10
  • how about your searchform.php and search.php code?
    – kaiser
    Commented Sep 26, 2011 at 17:00
  • I am using the bones theme which has a search.php but uses the core searchform
    – Drai
    Commented Sep 26, 2011 at 18:44
  • 2
    This is a general WordPress issue not a theme specific issue
    – Tom J Nowell
    Commented Oct 28, 2011 at 14:07

8 Answers 8

18

Here are 3 ways of fixing this, I advise you use solution 2, but pay attention to the jQuery in solution 1 as a way of avoiding the situation in the first place.

For those wanting more code posted from the question askers theme, this is not a theme issue, this is a general WordPress issue that affects all WordPress sites.

Solution 1

You can find an in depth tutorial on how to fix this here:

http://wpengineer.com/2162/fix-empty-searches/

Today, let’s look at something, that most professionals never see: empty searches. You offer a search input field, and someone hits the submit button unintentionally, without any term entered. The resulting URI looks like this: example.com/?s=. It shows the same content as your front page. In fact, it is the front page.

No one needs that.

Solution 2 (recommended)

Taken froma post by Spitzerg http://wordpress.org/support/topic/blank-search-sends-you-to-the-homepage

Another option is to add a request filter:

add_filter( 'request', 'my_request_filter' );
function my_request_filter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
    }
    return $query_vars;
}

Then if you're reusing the search query in your search form don't forget to trim it so you don't end up with one or more spaces (just to keep things clean, probably won't affect results.

<input type="text" name="s" id="s" value="<?php echo trim( get_search_query() ); ?>"/>

Hope this helps, it seems to be working thus far on my site and doesn't involve changing any of the WP code making upgrades easier.

Solution 3

http://www.warpconduit.net/2011/08/02/fix-redirection-and-error-page-on-empty-wordpress-search/

Similar to solution 2 but not as extensive and slightly different.

    if(!is_admin()){
        add_action('init', 'search_query_fix');
    }
    function search_query_fix(){
        if(isset($_GET['s']) && $_GET['s']==''){
            $_GET['s']=' ';
        }
    }
3
  • 1
    The problem with solution 2 is that it will return every post (or at least every post with a space in it) when really it should return no posts at all.
    – Felix Eve
    Commented Sep 2, 2014 at 5:10
  • It also doenst fix domain.com/page/2
    – fdrv
    Commented May 20, 2020 at 5:49
  • space is just what I used as a placeholder, you might consider using something you know will never appear in your content instead, but I couldn't think of something suitable at the time. Also, there is more than one solution
    – Tom J Nowell
    Commented May 20, 2020 at 18:44
3

Building on Tom's solution 2 but making sure no posts are returned add a request filter as before:

add_filter( 'request', 'my_request_filter' );
function my_request_filter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
        global $no_search_results;
        $no_search_results = TRUE;
    }
    return $query_vars;
}

But this time set a global variable to say no search results should be returned. Then using a posts_where hook make sure no posts are returned:

add_filter( 'posts_where' , 'posts_where_statement' ); 
function posts_where_statement( $where ) {
    global $no_search_results;
    if($no_search_results) {
        $where .= ' AND 1=0';
    }
    return $where;
}
1
  • Thanks so much for the snippet. It was driving me crazy that it would return all posts when not searching anything. Commented Dec 28, 2021 at 15:44
2

Create a Page Search.php and paste this code and change your loop with "get_template_part('loop', 'search');

                    <div id="container">
                        <div id="content" role="main">

            <?php if ( have_posts() ) : ?>
                            <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'mb' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
                            <?php
                            /* Run the loop for the search to output the results.
                             * If you want to overload this in a child theme then include a file
                             * called loop-search.php and that will be used instead.
                             */
                             get_template_part( 'loop', 'search' );
                            ?>
            <?php else : ?>
                            <div id="post-0" class="post no-results not-found">
                                <h2 class="entry-title"><?php _e( 'Nothing Found', 'mb' ); ?></h2>
                                <div class="entry-content">
                                    <p><?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'twentyten' ); ?></p>
                                    <?php get_search_form(); ?>
                                </div><!-- .entry-content -->
                            </div><!-- #post-0 -->
            <?php endif; ?>
                        </div><!-- #content -->
                    </div><!-- #container -->

            <?php get_sidebar(); ?>
            <?php get_footer(); ?>
1

Check if search query is empty ( get_search_query() ), just replace the first IF by that:

<?php if (have_posts() && get_search_query()) : while (have_posts()) : the_post(); ?>
1
  • I think this is fair enough solution. Simple and clean. No special filters and action which can complicate code
    – Kamil
    Commented Sep 24, 2019 at 14:23
0

I handle it in my themes as follows. Try using this code:

<?php if (!have_posts()): ?>
    <article id="post-0">
        <header>
            <h3>No posts found.</h3>
        </header> <!-- end article header -->

        <section class="post_content">
           Sorry, we found 0 posts for your search, Please try searching again.
        </section> <!-- end article section -->

        <footer>
        </footer> <!-- end article footer -->

    </article> <!-- end article -->
<?php endif; ?>

We're handling the if(!have_posts()) condition. Put it right after your h3.archive title, before if(have_posts) starts. You can even call the search form function in the content area.

0

I also faced the same problem, it is default given by wordpress.

but luckily I found something which helped me.

Add below in "Functions.php"

 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');

and then replace below line(line no 15) in search.php

<?php if ( have_posts() && strlen( trim(get_search_query()) ) != 0 ) : ?>

Might be it will help you too

For details read this : Customize empty search wordpress

0

One way to avoid empty search is to perform javascript check for empty value of the search field and if found field empty then stop submitting the search form like below:

$('#searchform').submit(function(){

            search_value =$.trim($('#searchform #s').val());

            if(search_value == ""){

                return false; // You can also pop a notification here to inform to user.
            }

});
0
# Catch empty searches
RewriteCond %{QUERY_STRING} ^s=$
RewriteRule ^ /? [L,R=301]
1
  • It's unclear how this answers the question. Could you edit your answer ( using the edit button above ) and add some detail on what this code does, where to put it, and how it solves the problem, please?
    – Howdy_McGee
    Commented Feb 28, 2017 at 20:29

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.