0

This code goes into an infinite loop! What am i doing wrong? There is only one post called “hello there”. The only way to stop it is use break; in while.

Any help appreciated

 $gotop="hello there";

$args = array(

    's' => $gotop,
    'post_type' => 'post'

);

$wp_query = new WP_Query($args);

if ( $wp_query->have_posts() ) :  ?>

        <?php

        while ( $wp_query->have_posts() ) {
      $wp_query->the_post();
}

else:
  echo "nothing found.";
endif;
?>
  • Don't use $wp_query as the variable name for your custom query. It's reserved for the main query. Can I ask why you're using a custom query for search? Is this your search.php template? – Jacob Peattie Jun 28 '19 at 11:16
  • i need custom query. i have to search for 'hello there' in my content-single.php – stefanosn Jun 28 '19 at 11:48
  • you were right the $wp_query was the issue. i renamed it and worked! please write the answer to accept it! – stefanosn Jun 28 '19 at 11:53
2

I'm not certain why it would cause an infinite loop, but make sure not to use $wp_query as the variable name for your custom query. It's a reserved global variable for the main query. Use a different name for the variable. I'd also suggest using wp_reset_postdata() after the loop:

$my_query = new WP_Query( $args );

if ( $my_query->have_posts() ) :
    while ( $my_query->have_posts() ) {
        $my_query->the_post();
    }
else:
  echo "nothing found.";
endif;

wp_reset_postdata();
1

add wp_reset_query(); after while loop.

$gotop="hello there";

$args = array(

    's' => $gotop,
    'post_type' => 'post'

);

$my_query = new WP_Query($args);

if ( $my_query->have_posts() ) :  

        while ( $my_query->have_posts() ) {
             $my_query->the_post();
        }
        wp_reset_query();

else:
  echo "nothing found.";
endif;

let me know if this works for you!

  • 1
    works but the problem was the $wp_query name... i changed it to another random name and it worked! – stefanosn Jun 28 '19 at 11:54
-1

According to WP codex, have_posts() will return True on success, false on failure. Calling this function within the loop will cause an infinite loop. So you need to use endwhile;

    $gotop="hello there";

$args = array(

    's' => $gotop,
    'post_type' => 'post'

);

$wp_query = new WP_Query($args);

if ( $wp_query->have_posts() ) :  ?>

        <?php

        while ( $wp_query->have_posts() ) {
      $wp_query->the_post();
      endwhile;
}

else:
  echo "nothing found.";
endif;
?>
  • This will cause a fatal error. They already have an endwhile, because they opened the while statement with a {, so it needs to be closed with a }, which they have. – Jacob Peattie Jun 28 '19 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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