Develop using WordPress Coding Standards

Programming nowadays, it becomes fundamental with Coding Standards. The goal is to maintain the same style, so that when you look at it you can interpret it easily.

What is Coding Standards?

The Coding Standards are style rules when developing, which allow us a better reading and understanding of the functions.

It tries to establish the best ways to work in WordPress and it is also not only based on style but also on best practices.

Why code style is important

Even if you’re working on a private project, the formatting of your code speaks volumes. And if you’re in a multi-developer environment, it says a lot more. Well-styled and well-thought-out code shows quality (even if it’s not good), while chaos breeds sloppy (even if it’s great) programming.

Here are some reasons to pay attention to the style of your code:

.

  • The styled code is easier to maintain. You may know what’s going on today, but what’s going to happen a year from now? Taking the time to structure your work will save you hours later on.
  • Other developers don’t read your mind, so they won’t understand your chaotic code, or will need a lot of time to untangle it. Ensuring as little friction in communication as possible is best for the project, and this can be facilitated by a standards-compliant format.
  • Slightly less important, someone learning to program should be able to visit a website and learn something by looking at the source code. Standards often have inherent logic, so a bystander would be able to figure out what is going on. Adhering to standards could help many developers who are starting to learn to program the right way from day one.
  • In many cases, good formatting helps maintainability. Many standards require spacing of declarations and other code blocks. Not cramming code together will make an “Error on line 267” message much easier to fix.

Configuration process on Mac

This is my process that I keep updated for setting up Coding Standards on Mac. There are several ways to install it, the one I like the most and is the one I expose, is with composer. For those who don’t know it is a software for php based libraries to integrate in your projects in a very easy way. It also allows a global installation which is what we will do. Then to keep all the libraries updated is very easy with this command:

composer global update

Install Composer on MacOs

Composerwith BREW

If you have brew, the package installer for macOS.

brew install composer

And you’re done! Much easier.

Composer (getcomposer.org) manually

We follow the steps below which really worked for me. We open the terminal and run the following commands:

.

curl -sS https://getcomposer.org/installer | php

And move that composer.phar file to the binary directory /usr/local/bin. Make sure that this folder is there before.

sudo mv composer.phar /usr/local/bin/

And we change its permissions:

sudo chmod 755 /usr/local/bin/composer.phar

Let’s add .profile

nano ~/.profile

And we add an alias to use it easily:

alias composer="php /usr/local/bin/composer.phar"

We continue in the terminal:

source ~/.profile

And finally check that Composer has been installed correctly:

composer -v
composer mac configuration

Configuring Code Sniffer and WordPress Standards

My installation instructions are based on working with Composer, the famous PHP library manager, as afterwards to update all our libraries is done with a single command:

composer global update

On the other hand, if you have installed it in other folders as, for example, recommends Ahmad Awais, then keeping them up to date becomes very complicated.

We install on our computer, the CodeSniffer version.

PHP_CodeSniffer is a set of two PHP scripts; the main phpcs script that logs PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second phpcbf script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures that your code stays clean and consistent.

composer global require "squizlabs/php_codesniffer=*"

We allow composer to allow the configuration globally.

composer global config bin-dir --absolute

Within Composer, we created a Coding Standards project for WordPress. It is a library created to manage the recommended rules within WordPress.

composer global require "wp-coding-standards/wpcs"

Once that project is downloaded, we tell PHPCS to manage the Coding Standards rules, at our location.

Remember to customize .composer/vendor/wp-coding-standards/wpcs with the location of the WordPress project

phpcs --config-set installed_paths $HOME/.composer/vendor/wp-coding-standards/wpcs 

If this command doesn’t work for you, ultimately the .composer/vedor/squizlabs/php_code_snifer/CodeSniffer.conf file should contain this information:

<?php
 $phpCodeSnifferConfig = array (
  'installed_paths' => '/Users/USER/.composer/vendor/wp-coding-standards/wpcs',
  'default_standard' => 'WordPress',
)
?>

Where installed_paths contains the directory where you have installed the Coding standards.

Finally, we define the rule we will use. We have:

  • WordPress – complete set with all the rules of the project
    • WordPress-Core – main rules for WordPress core coding standards
    • WordPress-Docs – additional rules for WordPress inline documentation standards.
  • WordPress-Extra – extended set of rules for recommended best practices, which are not sufficiently covered in the basic WordPress coding standards, includes WordPress-Core.

Let’s give PHPCS the path to the WordPress coding standards:

phpcs --config-set installed_paths $HOME/.composer/vendor/wp-coding-standards/wpcs 

.



And we set up the full WordPress set.

phpcs --config-set default_standard WordPress 

.

And now we can enjoy Coding Standard's recommendations in our favorite editor.

Adaptations-in-VisualCode-for-WordPress Coding Standards

.

Finally if we use Visualcode, we will need to configure where the phpcs executable is, which will come from our composer binaries folder. Add these lines in your JSON settings (check the executable):

// PHPCS. "phpcs.executablePath":"/Users/USERS/USER/.composer/vendor/bin/phpcs", // PHPCBF. "phpcbf.onsave": false, "phpcbf.standard": "WordPress", "phpcbf.executablePath":"/Users/USERS/USER/.composer/vendor/bin/phpcbf", "phpcs.ignorePatterns": ["*/vendor/*", "*/vendors/*"],

.

To enable integration with our Coding Standards editor, which in the end is what makes us implement it, we will install the VisualCode phpcs extension.

phpcs vscode extension

It is a preprocessor Lint, which is pointing out at all times the errors and improvements that when placed on top, shows us the error to correct.

phpcs underline

underline phpcs explanation

Upgrading to version 3.0

composer global update wp-coding-standards/wpcs --with-dependencies

Conclusion

.

Having the WordPress Coding Standards integrated in our editor is fundamental to write a safer, cleaner and easier to read code. And the integration is a must to get it up and running.

Sources:

Crea Bloques de Gutenberg con PHP y CSS y mesa redonda desarrollo

Páginas Web en Multidioma con WordPress

7 thoughts on “Develop using WordPress Coding Standards”

  1. Buenas David muchas gracias por compartir esto.
    Me surge una duda con esta parte:
    Recuerda personalizar .composer/vendor/wp-coding-standards/wpcs con la ubicación del proyecto de WordPress

    phpcs –config-set installed_paths $HOME/.composer/vendor/wp-coding-standards/wpcs

    Dónde estás indicando en esta instrucción la ubicación del proyecto WordPress?

    Gracias!
    Saludos

    Reply

Mentions

Mentions

  • David Pérez
  • Jorge

Leave a Comment

ÚLTIMOS ARTÍCULOS

Cierre Ventana

A great year on the WordPress plugin team

It’s been a great year for the WordPress Plugins Team. You can see the numbers in a summary…

Cierre Ventana

Develop more secure WordPress Plugins

Introduction Plugin Check Plugin is the new tool available to everyone that allows you to do automatic reviews…

Cierre Ventana

Create your own WordPress plugin, from scratch or already knowing some

Speakers: Francisco Torres, Paco Marchante and myself, David Pérez. We had the opportunity to be at WordCamp Madrid…

Logo David
Privacy Resume

Esta web utiliza cookies para que podamos ofrecerte la mejor experiencia de usuario posible. La información de las cookies se almacena en tu navegador y realiza funciones tales como reconocerte cuando vuelves a nuestra web o ayudar a nuestro equipo a comprender qué secciones de la web encuentras más interesantes y útiles.Para más información consulta nuestra <a href="/politica-privacidad/">Política de Privacidad</a>