I have a custom post type that I'm searching through with a custom query. I want to output a message if there's too many results (that works fine). But the problem I have is when you first goto the page and no search has been performed, I don't want that message to appear. How can I stop it appearing when no search has been performed?
<?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'posts_per_page' => 5,
'post_type' => 'researchdatabase',
'post_status' => 'publish',
'paged' => $paged
);
if($searchTerm != "") {
$args['s'] = $searchTerm;
}
$the_query = new WP_Query($args);
if ($the_query->have_posts()) {
$counter = 1; ?>
<p>
<b><?php echo $the_query->post_count; ?> research items</b>
<?php if($the_query->post_count > 20) { ?>
<br /><span class="research-alert"><b>Refine your search criteria to see fewer results.</b></span>
<?php } ?>
</p>
<hr />
<br />
<?php while ($the_query->have_posts()) { $the_query->the_post(); ?>
<?php // output results ?>
<?php $counter++;
} // end while
// reset post data
wp_reset_postdata();
} else {
echo 'No results';
} // end if
?>
Just change the condition:
<?php if($the_query->post_count > 20) { ?>
With:
<?php if($the_query->post_count > 20 && is_search()) { ?>
is_search()
return true if any search term is sent for the current WP_Query
.
"no search has been performed" equals "no search term in the query", why don't you just check search term first?
if(!empty($searchTerm)) {
$args = array(
's' => $searchTerm
'posts_per_page' => 5,
'post_type' => 'researchdatabase',
'post_status' => 'publish',
'paged' => (get_query_var('paged')) ? get_query_var('paged') : 1
);
$the_query = new WP_Query($args);
// Your code.
}
BTW: if you want to display total count of search results, you should use $the_query->found_posts
not $the_query->post_count
it only count posts on first page.