I am trying to build my search results page, and I am using wp_query. However, overtime I search something all of my posts are showing up instead of only those posts that match the search. Why is this, and how can I fix this?

get_header(); ?>
$args = array(
'posts_per_page' => 4
$search_query = new WP_Query( $args );
if ( $search_query->have_posts() ) : 
<div class="search-results-search">
<form role="search" method="get" class="search-form-search form-inline-search" action="">
            <div class="input-group-search">
                <input type="search" value="" name="s" class="input-sm-search search-field-search form-control-search" placeholder="<?php echo $s ?>">
<?php while ( $search_query->have_posts() ) : $search_query->the_post() ?>
<article <?php post_class( 'col-sm-6 col-md-6' ); ?>> 
<?php the_post_thumbnail('full', array('class' => 'medium-front-thumbnail')); ?> 
<div class="front-page-date"><?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago'; ?></div>
<h2><a class="front-page-post-title" href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> 
<p class="front-page-post-excerpt"><?php echo get_the_excerpt(); ?></p> 
<div class="front-page-post-info"> 
<a class="moretext" href="<?php the_permalink(); ?>">Read more</a>
<?php get_template_part( 'front-shop-the-post' ); ?>
<?php get_template_part( 'share-buttons' ); ?>
    <div class="front-comments"><?php comments_popup_link ('0', '1', '%', 'comment-count', 'none'); ?></div> 

<?php endwhile ?>
<?php else : ?>
<h2>Ooops, no posts here!</h2>
<?php endif ?>

get_footer(); ?>
  • 1
    Are you sure the code above is the cause of the issue? Are you certain that this template is being called? Maybe there's a pre_get_posts in your theme somewhere overwriting your query. What happens if you run print_r( $search_query ); die(); after your create a new WP_Query()? Can you edit your question and add in some additional information please? – Howdy_McGee Jun 23 '17 at 23:54
  • you are missing to use the 'search' parameter - codex.wordpress.org/Class_Reference/WP_Query#Search_Parameter – Michael Jun 24 '17 at 0:14
  • How would I add the search parameter in my code? When I tried adding it, it did not work. – user7548188 Jun 24 '17 at 2:56

Don't create a new WP_Query. As per the template hierarchy WordPress uses the search.php template in your theme for the search results page. This template just needs to contain The Loop, and the only posts inside that will be your search results.

See Twenty Seventeen's search results template as an example: https://github.com/WordPress/twentyseventeen/blob/master/search.php

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.