1

We often see this insdie the WordPress templates:

while ( have_posts() ) : the_post();
...
endwhile;

Do you have any idea why not using braces or "curly brackets" {} for while loop? What is the gain?

1

According to the wordpress handbook on php coding standards, braces should be used for all blocks in the style shown below:

if ( condition ) {
    action1();
    action2();
} elseif ( condition2 && condition3 ) {
    action3();
    action4();
} else {
    defaultaction();
}

The use of braces means single-statement inline control structures are prohibited so it's better to use the alternative syntax for control structures (e.g. if/endif, while/endwhile) in this scenario, especially in template files where PHP code is embedded within HTML:

<?php if ( have_posts() ) : ?>
    <div class="hfeed">
        <?php while ( have_posts() ) : the_post(); ?>
            <article id="post-<?php the_ID() ?>" class="<?php post_class() ?>">
                <!-- ... -->
            </article>
        <?php endwhile; ?>
    </div>
<?php endif; ?>
  • I am not stingy on points when my questions are in question, this was so close I really several times upvoted and then reset, eventually something prevail to the upvote, but I haven't seen what is the gain? – prosti Jan 5 '17 at 23:08
  • 1
    And please don't mix this with wordpress.stackexchange.com/questions/220682/…, after a check I saw your answer is almost identical with one answer from there. – prosti Jan 5 '17 at 23:31
  • I just quoted the documentation mostly, the key point being the prohibition of single-statement inline control structures – Tunji Jan 5 '17 at 23:32
  • I see now sorry, so you don't see any gain? @TunjiAyoola – prosti Jan 6 '17 at 8:10
0

It's just another way of writing it, mostly a stylistic choice. I use while loops with curly brackets, and find while : endwhile very hard to read.

Edit: previously asked here. tl;dr: same 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.