2

Is there a way to make a conditional tag that tests if it is search-no-results page?

I know that there is a function to check if is_search() page:

if(is_search()){
    echo "search page";
}

But I didn't found a way to check for search-no-results, and I noticed that WordPress gives body class with search-no-results to this page.

3 Answers 3

7

There is no conditional tag for no results on a search page, but you can create yourself one.

You basically just have to check the value of $wp_query->found_posts, if it is 0, returns false, any other value, returns true

function is_search_has_results() {
    return 0 != $GLOBALS['wp_query']->found_posts;
}
2
  • Vote Up requires 15 reputation... :( vote my question and maybe then i will can vote your answer Commented Dec 22, 2014 at 13:37
  • great, using it as a condition, thanks!
    – Iggy
    Commented Aug 5 at 18:29
2

Actually it should be like this.

function is_search_has_results() {
  if ( is_search()) {
    global $wp_query;
    $result = ( 0 != $wp_query->found_posts ) ? true : false;
    return $result;
  }
}
0

Why not use code like this in your search.php template :

if ( have_posts() ) {

    return default search results query

} else {

    Your custom query

}

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.