-
Notifications
You must be signed in to change notification settings - Fork 0
Code Style
The following suggestions all improve code that will technically pass WP coding standards and Square Candy's PHP linting. Used all together, these can substantially reduce the deepest tab level and generally make for more readable and maintainable code.
Left align all if else statements in the same way at the start and end. This applies to foreach, and so on too.
No:
<?php if ( $example ) : ?>
<p>Example!</p>
<!-- lots more code here -->
<?php
endif;
Yes - even if the extra php tags at the end seem excessive:
<?php if ( $example ) : ?>
<p>Example!</p>
<!-- lots more code here -->
<?php endif; ?>
<?php // more php code here.
Yes - even if if seems like a lot of line breaks in the opening if:
<?php
if ( $example ) :
?>
<p>Example!</p>
<!-- lots more code here -->
<?php
endif;
// more php code here.
Inline functions are fine for very short snippets, but anything longer than 5-6 lines of code, it's best to avoid the extra level of indentation by using a separate function.
add_action(
'existing_wp_hook',
function( $id ) {
// our custom code starts 2 tabs in.
Better in most cases:
add_action( 'existing_wp_hook', 'squarecandy_existing_wp_hook', 10, 1 );
function squarecandy_existing_wp_hook( $id ) {
// our custom code starts 1 tab in.
Use negative conditions to bail out early instead of wrapping entire functions in an if statement.
No:
function squarecandy_sample_function( $bloop ) {
if ( $bloop ) :
// very long php code here.
// this starts 2 tabs in.
endif;
}
Yes:
function squarecandy_sample_function( $bloop ) {
// bail if this is not a Bloop
if ( ! $bloop ) {
return;
}
// very long php code here.
// this starts 1 tab in.
}
Use comments to keep track of closing tags in very long nested code situations - both HTML and PHP. Implement this anytime the closing tag is more than 20 lines away from the opening.
No: (Technically passing, but hard to keep track of closing divs and ifs)
function squarecandy_sample_function( $bloop ) {
if ( $bloop ) :
?>
<div class="bloop">
<p>Some content</p>
<?php if ( $blorp ) : ?>
<p>Some more content</p>
<?php if ( $beep ) : ?>
<p>Even more content</p>
<?php endif; ?>
<div>Sample</div>
<?php endif; ?>
<?php // etc... very long php code here. ?>
</div>
<?php
endif;
}
Yes:
function squarecandy_sample_function( $bloop ) {
if ( $bloop ) :
?>
<div class="bloop">
<p>Some content</p>
<?php if ( $blorp ) : ?>
<p>Some more content</p>
<?php if ( $beep ) : ?>
<p>Even more content</p>
<?php endif; ?>
<div>Sample</div>
<?php endif; ?>
<?php // etc... very long php code here. ?>
</div> <!-- .bloop -->
<?php
endif; // end if $bloop
}