Chapters

PHP Coding Standards

Naming Convention

Files should be named descriptively using lowercase letters. Hyphens should separate words: my-file-name.php

Indentation

Your indentation should always reflect logical structure. Use real tabs, not spaces, as this allows the most flexibility across clients.

Exception: if you have a block of code that would be more readable if things are aligned, use spaces:

        
            [tab]$foo   = 'somevalue';
[tab]$foo2  = 'somevalue2';
[tab]$foo34 = 'somevalue3';
[tab]$foo5  = 'somevalue4';        
    

Syntax

Please use the alternative syntax when writing control structures that mix PHP and HTML. This will help tremendously with readability. It may look fine to use the curly braces for your control structures, but it starts to get very easy to lose where a curly brace starts and where it ends on larger, more complex code blocks.

Correct

        
            /** If statement */
<?php if( $title ) : ?>
    <h1><?= $title; ?></h1>
<?php endif; ?>

/** If/Else statement */
<?php if( $title ) : ?>
    <h1><?= $title; ?></h1>
<?php else : ?>
    <h1><?= get_bloginfo( 'name' ); ?></h1>
<?php endif; ?>

/** Foreach loop */
<?php foreach( $categories as $category ) : ?>
    <span class="cat-tag"><?= $category->cat_name; ?></span>
<?php endforeach; ?>

/** While loop */
<?php if( $query ) : ?>

    <?php while( $query->have_posts() ) : $query->the_post(); ?>

        <?php get_template_part('inc/card-content'); ?>

    <?php endwhile; ?>

<?php else : ?>

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

<?php endif; wp_reset_postdata(); ?>        
    

Incorrect

        
            /** If statement */
<?php if( $title ) { ?>
    <h1><?= $title; ?></h1>
<?php } ?>

/** If/Else statement */
<?php if( $title ) { ?>
    <h1><?= $title; ?></h1>
<?php else : ?>
    <h1><?= get_bloginfo( 'name' ); ?></h1>
<?php } ?>

/** Foreach loop */
<?php foreach( $categories as $category ) { ?>
    <span class="cat-tag"><?= $category->cat_name; ?></span>
<?php } ?>

/** While loop */
<?php if( $query ) { ?>

    <?php while( $query->have_posts() ) { $query->the_post(); ?>

        <?php get_template_part('inc/card-content'); ?>

    <?php } ?>

<?php } else { ?>

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

<?php } wp_reset_postdata(); ?>