I’ve created a search page and using the loop return results based on users input. Problem is when I go to the search page it displays the search page title when the user hasn’t entered anything. Is there a way I can remove the search page from the results? I’ve tried plugins but they don’t work – am convinced there is something wrong with my loop but I don’t see it.
My code is:
<?php
/*
Template Name: Search Page
?>
<?php get_header(); ?>
<section id="post-<?php the_title(); ?>" class="search-section left <?php post_class(); ?>" role="main">
<div class="search-input">
<form action="<?php echo home_url(); ?>" method="get" role="search" class="search-big">
<input type="text" name="s" id="s" class="search-big" placeholder="Type in your search and press enter..." />
</form>
</div>
<div class="search-result">
<?php if ( have_posts() ) : ?>
<h2><?php if( !empty( $_GET) ) { printf( __( 'Search results for: %s', 'xma' ), '<span>' . get_search_query() . '</span>' ); } ?></h2>
<?php while ( have_posts() ) : the_post(); ?>
<div class="search-single-result">
<a href="<?php the_permalink(); ?>"><h4><?php the_title(); ?></h4>
<p><?php the_excerpt(); ?></p></a>
</div>
<?php endwhile; ?>
<?php else : ?>
<h3><?php _e('Sorry, we couldn't find anything that matched your search.', 'xma' ); ?></h3>
<?php endif; ?>
</div>
</section>
<aside class="search-sidebar right">
<?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?>
<?php dynamic_sidebar( 'sidebar-4' ); ?>
<?php endif; ?>
</aside>
screenshot of bug thats happening:
Basically from my understand, you want it so that if the user goes to the search page, they don’t see a title on the page that says ‘Search Results for: ‘ with nothing after the colon. I have a proposed code change that will eliminate the title, and allow you to put a message for the user to search for something, to display results.
There are two code blocks to add, one up top, and one down low. Hope this helps!
EDIT (after clarification)
After we talked, it looks like the problem is related to the fact that you have a custom URL for the search page, something like ‘/search’, which is actually a WordPress page labeled ‘Search’. The problem is that when you load this search page, your loop already has one result in it, the current page. What you need to do is first check if your current loop is for the search, or if it is for the display of the search page. Do this like so:
Keep the lower lines, and change those top lines to what I have. This is going to check that your loop is actually the loop that has the results of the search in it. If it is, then it draws the results, if not, then it displays the message below.
Try this method which I found WordPress StackExchange
Let me know if it works, or need improvement