Empty search input returns all posts

Question

So today I’ve decided to implement a search form onto my site that obviously returns a result when the user searches for it, but I’ve run into a little problem.

My Problem

When the user searches for a result without inputting anything into the search form for some reason it returns 5 Pages whereas I would like it to return a Message that says something along the lines of ‘Search Fields was empty – Search Again’.

How would I go about making this happen? I’ve inserted my code below that controls my searchform button and the content it outputs when search.

Code Controlling the Search Form

searchform.php This is the Search form which is where the user inputs what they want (I have a feeling I need to enter some code here to check if it is empty)

<form role="search" method="get" id="searchform" action="<?php echo home_url('/'); ?>">
    <div>
        <label class="screen-reader-text" for="s">Search: </label>
        <input type="text" value="" name="s" id="s" placeholder="<?php the_search_query(); ?>" />
        <input type="submit" id="searchsubmit" value="Search" />
    </div>
</form>

search.php This is showing the user what they have searched for and the getting the template content-search to show the Page name(s).

<div class="search-result">
    <div class="container">
        <div class="row">
            <div class="search">
                <?php if (have_posts()) : ?>

                    <h2>Search Result For: <?php the_search_query(); ?></h2>
                    <div class="light-separator small center"></div>

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

                    get_template_part('content-search', get_post_format());

                    endwhile;
                    else :
                        echo '
                        <div class="no-content"> 
                            <h3>Ooopss, looks like nothing matches your result.</h3>
                        </div>';
                    endif;
                ?>
                <div class="search-form"><?php get_search_form(); ?></div>
            </div>        
        </div>
    </div>
</div>

content-search.php – This displays the Pages Title and the Permalink for the Page

<div class="searchs">
    <h4>Pages - <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
</div>
0
Stephen 1 year 2020-07-11T01:11:00-05:00 0 Answers 40 views 0

Leave an answer

Browse
Browse