runeveryday
runeveryday

Reputation: 2799

Wordpress's loop

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

While it use while(have_posts()), I feel it's useless. Suppose it doesn't have the while condition, the first if(have_posts()) to check the block whether have a post. If there is no post, the programme goes out the loop. if there is a post, then execute the_post(). Any tips would be appreciated.

Upvotes: 0

Views: 240

Answers (2)

ariefbayu
ariefbayu

Reputation: 21979

First, it check if there are posts to display on that particular page using:

if(have_posts())

if there are any, it will loop through each post using:

while(have_posts())

Right after that, it extract post's data using:

the_post();

As for the syntax it self, it uses what is called ternary operation (CMIIW here).

For more detailed explanation, you can read about the loop on wordpress codex. Here's a little explanation taken from that page:

Once WordPress has finished loading the blog header and is descending into the template, we arrive at our post Loop. The have_posts() simply calls into $wp_query->have_posts() which checks a loop counter to see if there are any posts left in the post array. And the_post() calls $wp_query->the_post() which advances the loop counter and sets up the global $post variable as well as all of the global post data. Once we have exhausted the loop, have_posts() will return false and we are done.

Upvotes: 1

nonopolarity
nonopolarity

Reputation: 151244

The loop construct will repeat and repeat. The construct like

while(have_posts())

will repeat until there is no more post. So its returned value is not always the same. It helps to repeat the content of the loop again and again, until there is no more post, when have_posts() return a false value for the while loop to stop.

Upvotes: 1

Related Questions