0

I've written this code but cannot work out why it's triggering an infinite loop. I have hunted around for similar issues but nothing is clicking for me. Can anyone please shed some light?

<?php
$args = array(
        'post_type'         => 'post',
        'posts_per_page'    => 3
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : ?>

<div class="news_item">

    <img src="<?php echo get_template_directory_uri(); ?>/img/dummy.png">
    <h3><a href="#">Government introduces X Y Z for lorem ipsum dolor esters.</a></h3>

</div>

<?php endwhile; endif;
wp_reset_postdata(); ?>

1 Answer 1

2

You did forget to increment the post iterator inside The Loop. This iterator points to the next post. Since you are not incrementing it by calling the_post() inside the loop, have_posts() will always return true.

A basic example how to programm The Loop and how to use the_post() and have_posts() is shown here:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

Some nice Markup goes here...

<?php endwhile; else : ?>
  <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

(Taken from here: Wordpress.com, The Loop, 1 - Using the Loop, Last time accessed at 30.12.2015)

Additionally a note to the_post():

Iterate the post index in The Loop. Retrieves the next post, sets up the post, sets the 'in the loop' property to true.

(Taken from here: Wordpress.com, Function Reference/the post, last time accessed at 30.12.2015)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.