PHP Coding Standards

Table of Content

1. General

1.1 Opening and Closing PHP Tags

When embedding multi-line PHP snippets within an HTML block, the PHP open and close tags must be on a line by themselves.

// Multi line
function foo() {
    ?>
    <div>
        <?php
        echo esc_html(
            bar(
                $baz,
                $bat
            )
        );
        ?>
    </div>
    <?php
}
// Single Line 
<input name="<?php echo esc_attr( $name ); ?>" />

1.2 No Shorthand PHP Tags

Incorrect

<? ... ?>
<?= esc_html( $var ) ?>

Correct

<?php ... ?>
<?php echo esc_html( $var ); ?>

1.3 Single and Double Quotes

Always use single quote, only use double quote when required

echo '<a href="/static/link" class="button button-primary">Link name</a>';
echo "<a href='{$escaped_link}'>text with a ' single quote</a>";

1.4 Writing include/require statements

It is recommended to use require over include. As it throws error and bugs can be fixed earlier

// Correct.
require_once ABSPATH . 'file-name.php';
 
// Incorrect.
include_once  ( ABSPATH . 'file-name.php' );
require_once     __DIR__ . '/file-name.php';

2. Naming Conventions

2.1 Lowercase letter and Underscore seperated

// Variables
$first_name = 'John';
 
// Actions/Filters
add_action('wp_head', 'custom_wp_head_action');
function custom_wp_head_action() {
    echo '<!-- Custom action in wp_head -->';
}
 
// Functions
function get_full_name($first_name, $last_name) {
    return $first_name . ' ' . $last_name;
}
💔 Note: With the introduction of named arguments in PHP 8.0, where you can call a function by explicitly naming its parameters, renaming a function parameter is considered Breaking change.

2.2 Capitalized words separated by underscores.

// Class
class User_Profile {
    // Class properties and methods
}
 
// Trait
trait Singleton_Trait {
    // Trait methods
}
 
// Interface
interface Loggable_Interface {
    public function log_message($message);
}
 
// Enum
enum User_Role {
    case Administrator;
    case Editor;
    case Subscriber;
}

2.3 Uppercase

2.4 File names

3. Whitespace

4. Formatting

4.1 Braces

Use Braces even if their is only one statement in this style

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

4.2 Declaring Arrays

4.3 Multiline Function Calls

$multiLineArray = array(
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
);
 
$multiLineString = "This is a long string that 
spans multiple lines.";
 
$functionReturn = someFunction(
    $multiLineArray,
    $multiLineString,
    'singleLineValue'
);