0

I'm creating a short code to display a table based on a custom post type. For some reason this is creating an infinite loop. Here is the code for the shortcode

  function cwf_enquiry_table_html()
  {
    $args = array(
      'post_type' => 'form-enquiry'
    );

    $form_enquiries = new WP_Query($args);

    if($form_enquiries->have_posts())
    {
      while($form_enquiries->have_posts())
      {
        echo '<p>' . get_the_title() . '</p>';
      }
    }

    // wp_reset_query();
  }
  add_shortcode('enquiry_table', 'cwf_enquiry_table_html');

Currently this is just returning "Home" constantly. I've got the shortcode on the home page so I presume it's pulling some other query and not the one I am trying to run. As you can see I tried to reset the query but it didn't fix anything.

4

You need $form_enquiries->the_post() to "push" the loop onto the next post - otherwise yes, you get an infinite loop!

while ( $form_enquiries->have_posts() ) {
    $form_enquiries->the_post();
    // rest of your loop
}
2
  • Thanks, I knew there was something obvious I was missing ... Marked as correct in case anyone else makes the same mistake. Dec 11 '16 at 14:55
  • @TheDeadMedic Awesome thanks for point $form_enquiries->the_post(); Feb 13 '17 at 10:08

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.