In most themes I've looked at and WordPress core, I'm seeing the use of endwhile
and endif
.
Is there a good reason why WordPress uses these instead of curly braces for block statements?
In most themes I've looked at and WordPress core, I'm seeing the use of endwhile
and endif
.
Is there a good reason why WordPress uses these instead of curly braces for block statements?
As in many things wordpress, inertia has a lot to do with why things are done in specific way. Early core themes were written using those constructs and later developers copied them because they either did not know better or thought there was some non obvious reason to prefer them.
As @Howdy_McGee said, it is just a style preference but I would avoid the endif
, endwhile
as curly braces are standard block delimiters across many languages and therefor are in general easier to read even if we will ignore the benefit of syntax highlighting and block collapsing in general editors.
The best reason I can find it to separate Logic from Structure or Control from Markup. The handbook on the PHP Coding Standard for WordPress says:
Braces should always be used, even when they are not required:
if ( condition ) { action0(); } if ( condition ) { action1(); } elseif ( condition2 ) { action2a(); action2b(); } foreach ( $items as $item ) { process_item( $item ); }
Note that requiring the use of braces just means that single-statement inline control structures are prohibited. You are free to use the alternative syntax for control structures (e.g. if/endif, while/endwhile) — especially in your templates where PHP code is embedded within HTML, for instance:
<?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; ?>
Some could argue that braces are better because of syntax highlighting ( i.e. click opening bracket and it highlights closing bracket ) but it comes down to preference. The alternative syntax isn't required or necessary but offered as an alternative so you're free to use whichever is the cleanest to read.
Personally, I use the alt syntax in templates ( or any time I plan on mixing HTML and PHP ) with appropriate spacing and indentation as I find it easier to read overall.
if( condition ) { ?> <HTML> <?php }
. As you said, alternative syntax of control structures is optional.
– cybmeta
Mar 14 '16 at 19:43