Why switching to – WordPress Coding Standards – will make you a better developer



Why switching to – WordPress Coding Standards – will make you a better developer

1 0


wp-coding-standards-talk

My "Why Switching to WordPress Coding Standards Will Make You A Better Developer" talk, which I've presented at several WordCamps and local WordPress meet-ups.

On Github davetgreen / wp-coding-standards-talk

Why switching to

WordPress Coding Standards

will make you a better developer

Dave Green

Front-end, WordPress & WooCommerce Engineer

davetgreen.me

@davetgreen

www.makedo.net

WordPress Development, Design and Support Agency

My Story

  • OCD so I love clear structures and standards.

  • Work on more team projects than ever.

  • Spending a lot more time writing plugins.

  • Trying to increase my contributions to core.

  • Make Do work with a lot of other agencies.

  • Have used PSR2 standards in the past.

  • Switched for PHP coding in September 2015.

  • In the process of switching for Javascript.

So what are they?

Rules your code should conform to, and will be checked against.

Developed for wordpress core, official themes and plugins.

Four language specific standards

  • PHP
  • JS
  • CSS
  • HTML

Accessibility Coding Standards

Approved for inclusion in the Core Handbook and announced to the communty in March 2016.

All new or updated code released in WordPress must conform with the WCAG 2.0 guidelines at level AA.

Core Handbook

Written by the community, for the community.

Have existed in some form or other since 2009.

A set of standards that will grow and evolve with WordPress.

What they are NOT.

Not just for the hardcore or rockstar types.

Not just for core contributors.

Not a definition of right & wrong.

Just the "WordPress way".

Not there to make you feel guilty.

Not going to add more complexity to your code.

10 Benefits of Switching to WPCS

(there are many more!)

Reduced Stress

No more worrying about how you should write code. Less stress = more code :)

Readable Code

Consistent indentation, spacing, structure, naming of things and much more.

Great for Teams

All code looks the same, regardless of who wrote it or when it was written, with no fingerprints.

Future Proofing

Warnings when you use deprecated functions to prevent unwanted surprises.

Faster Debugging

Bugs are quicker to find & fix because your code iseasier to read & understand.

Avoid Pesky Bugs

Evaluate expressions using Yoda conditions. Reverse the expression, you will.

if ( 'literal' == $variable ) {
if ( true == $variable ) {
if ( function() == $variable ) {

The common approach

$variable = 'wpcs';
if ( $variable == 'wpcs' ) {
    $result = 'Huzzah!';
}

Here we're checking to see if the variable is equal to the string literal. In this case the expression resolves as truthy, and we get the desired result.

Make mistakes, you will

$variable = 'ooops!';
// Ooops, we lost an equals!
if ( $variable = 'wpcs' ) {
    $result = 'Huzzah!';
}

Ommitting the second comparison operator (equals) means that this expression silently resolves as truthy, and is a bug that may take you several minutes to fix!

Reverse it, you shall

$variable = 'ooops!';
if ( 'wpcs' = $variable ) {
    $result = 'Huzzah!';
}

By reversing the expression, an ommission of the second comparison operator (equals) will produce an error that you can fix immediately. Huzzah!

Error, you will get

Parse error: syntax error,
unexpected '=' in /example.php
on line 5

Yoda Conditions should only be used with the following comparison operators: ==, !=, ===, and !==.

Better Inline Docs

Standards encourage more consistent and detailed documentation of your code.

File documentation

/**
 * A description of what purpose this
 * file serves in the theme/plugin.
 *
 * @package Example_Theme
 */

Function documentation

/**
 * Describe the function's purpose.
 * @param  int    $id    Post ID.
 * @param  array  $args  Arguments.
 * @return string        Some text.
 */
function do_something( $id, $args ) {

More Secure Code

Consistent validatation, sanitization and escaping of your input & output data.

Validating Input

Here we check to see if the input variable is a string as expected, before adding it to an array.

$things = array();
if ( isset( $_POST['foo'] ) {
    $foo = $_POST['foo'];

    if ( 'string' === gettype( $foo ) ) {
        $things[] = $foo;
    }
}

Sanitizing Input

Here we validate then sanitize an input variable before using it to update post meta.

if ( isset( $_POST['foo'] ) ) {
    $foo = sanitize_text_field( $_POST['foo'] );

    update_post_meta( $id, 'foo_meta', $foo );
}

Escaping output

Here we output a validated and sanitized input variable, making sure it has been properly escaped.

if ( isset( $_POST['foo'] ) {
    $foo = sanitize_text_field( $_POST['foo'] );
    echo '<h1>' . esc_html( $foo ) . '</h1>';
}

Better DB Queries

Avoid using WPDB for custom database queries in favour of the WordPress API.

(Caching and performance optimisation FTW!)

The WPDB Way

Lets get all posts with an ID less than 99.

global $wpdb;
$posts = $wpdb->get_results(
    "SELECT *
    FROM $wpdb->posts
    WHERE `id` < 99",
    OBJECT
);

The WP API Way

Pass an array of IDs into a new WP_Query and voila!

$ids = range(1, 98);
$args = array(
    'post__in' => $ids,
);
$my_query = new WP_Query( $args );

Easier to Maintain

Anyone can modify your code to fix or improve it right now or in the future.

Switching to WPCS for writing PHP

What you will need to "sniff" your PHP while you develop.

PHP Code Sniffer

Install PHPCS on your machine using PEAR or Composer. Homebrew is an alternative for Mac OSX users.

Add the path to the phpcs command to your system PATH, transforming it into a global installation.

Setting the path on OSX

Open your Bash profile, append the path to phpcs, save the file, reload it and then echo the PATH to test it.

nano ~/.bash_profile
export PATH=$PATH:/usr/local/bin/phpcs
CRTL+X
source ~/.bash_profile
echo $PATH

Get WPCS rules from GitHub

Download the WPCS rules for PHPCS to your machine using Git, Pear, Composer or the old fashioned way.

Place them in a suitable directory and make a note of the location. Mine are in: /Users/davetgreen/.wpcs

A Code Editor / IDE

Sublime
Atom
Netbeans
PHPStorm
Coda

Or any similar software that either has a PHP Code Sniffer plugin available or comes with built-in support.

Getting Ready

Install/enable the plugin or native PHPCS support. Add the path to the WPCS folder in your settings. Enable check on save to automatically sniff the code. Decide how you want to display errors in your code. Automatically fix many issues by enabling PHP CS Fixer.

Alternatively...

Command Line

Run PHPCS directly from the command line when needed.

$ phpcs --standard=WordPress test.php

Workflow

Automate the use of PHPCS as part of your build processes using Grunt, Gulp etc.

// A quick example
if($force == "with you") {
 $victorious = you_will($be);
}
  • Inline comments must end in full stops.

  • Expected 1 space after IF keyword.

  • No space after opening parenthesis is prohibited.

  • Use Yoda Condition checks, you must.

  • String "with you" does not require double quotes.

  • No space before closing parenthesis is prohibited.

  • Line indented correctly; expected 1 tabs, found 0.

  • Expecting one spaces before closing bracket: 0 found.

Before WPCS

// A quick example
if($force == "with you") {
 $victorious = you_will($be);
}

After WPCS

// A quick example.
if ( 'with you' == $force ) {
    $victorious = you_will( $be );
}

Some Advice

  • Don't try to switch for all languages/standards at once.

  • Gradually increase the amount of rules you comply with.

  • Mistakes are going to be made, it's part of the process.

  • Get help with the initial set-up if needed: it's worth it.

  • Productivity is key, don't let standards get in the way.

  • Encourage other WordPress developers to switch!

  • Code like you've never coded before!

Coding Standards for Theme Development

Useful Resources

Thank you!

Slides available at:davetgreen.me/wpcs-talk

@davetgreen

Questions?

Why switching to WordPress Coding Standards will make you a better developer