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;
?>
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;
?>
Share
Improve this question
asked Jun 28, 2019 at 10:54
stefanosnstefanosn
1339 bronze badges
3
|
3 Answers
Reset to default 2I'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();
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!
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;
?>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745362409a4624419.html
$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 Commented Jun 28, 2019 at 11:16