0

Why does this simple query break my site and lead to the following error:

502 Bad Gateway

I am using the category slug and yes I have exactly one post of this category. It is embedded in the header template part of a third-party theme.

 function bambam(){
     $args = array(
         'category_name' => 'breaking-news', 
         'post_date' => 'DESC',
         'posts_per_page' => 1
     );

     $the_query = new WP_Query( $args );

     if ( $the_query->have_posts() ) {
          echo '<div class="breaking-news">';
          while ( $the_query->have_posts() ) {
              echo '<h1>' . get_the_title() . '</h1>';
          }
          echo '</div>';
          /* Restore original Post Data */
          wp_reset_postdata();
      } else {
          // no posts found
      }
}
bambam();
1

It has nothing to do with WP_Query itself. The reason for such problem is what you do with this WP_Query. There’s no the_post() in your code, so the loop is infinite.

This is how to fix it:

 function bambam(){
     $args = array(
         'category_name' => 'breaking-news', 
         'post_date' => 'DESC',
         'posts_per_page' => 1
     );

     $the_query = new WP_Query( $args );

     if ( $the_query->have_posts() ) {
          echo '<div class="breaking-news">';
          while ( $the_query->have_posts() ) {
               $the_query->the_post();
              echo '<h1>' . get_the_title() . '</h1>';
          }
          echo '</div>';
          /* Restore original Post Data */
          wp_reset_postdata();
      } else {
          // no posts found
      }
}
bambam();
| improve this answer | |

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.