This week, I’m going to walk you through setting up a set of coding standards so you can maintain consistency in your WordPress plugin codebase.
One of the best ways to improve your plugin’s codebase is to establish a set of rules for how you format the code that you write.
Whether you work on your plugin in isolation, or with a team, it helps keep everything organized and standardized.
I’ve worked in lots of WordPress codebases over the last few years and unfortunately, most of them don’t adhere to a set of standards. Typically, you can tell who wrote each feature because the coding style looks completely different.
Coding standards help you stay consistent, secure, and performant
I think developers don’t have a set of coding standards for a few reasons.
- They don’t think they have the time
- They don’t understand how to get started
- They think it’s just another system to maintain
I’m going to show you that you can easily configure coding standards in a very short amount of time and gain massive benefits.
Here’s how, step by step:
Install WordPress Core’s Coding Standards
Since WordPress is a widely used open source project, all of it’s tools are also open sourced. One of these tools is the coding standards they have established across the codebase.
Since your plugin integrates with WordPress, following their standards is a great start when establishing your own standards.
1. Install Composer (If you haven’t done that yet, I’ve written about it here)
2. Require the WordPress Coding Standards in your plugin’s dev dependencies
3. Add a basic phpcs.xml configuration file to your project root
Once you’ve done these 3 things, you can start using it immediately from the command line in your project:
You can check individual files by running that command and you’ll get suggestions with the errors found.
Here’s what that looks like when checking Hello Dolly for issues:
Install Extensions in your Code Editor
I’m using VS Code on a daily basis and the best extension I’ve found that pulls in the installed coding standards is PHP Sniffer & Beautifier.
Here is what an issue looks like in my editor when looking through Hello Dolly:
Follow the Suggestions
Now that you have configured a basic standard for your project, you can spend a little time updating your codebase. I’d suggest setting up a single Pull Request that contains all the Coding Standards edits so it’s all grouped in together.
And now, when you’re writing your code, you’ll get nudged in the right direction as you write. It’ll improve the formatting of your code, give you security suggestions, and performance tips.
If you want to look deeper into the Coding Standards, you can check out the WordPress Developer Resources page.
I hope that helps get you started in your own plugin!