Stop Cowboy Coding: 10 Tips for Improving the Quality of Your WordPress Themes and Plugins
Stop Cowboy Coding: 10 Tips for Improving the Quality of Your WordPress Themes and Plugins
Not so long ago, Torque published a post bemoaning the quality of the code in ThemeForest’s themes. If you’re a WordPress user downloading or buying themes or plugins for use on your site, you’ll want to be confident that the themes and plugins you’re using are well-coded, reliable and secure.
But this doesn’t just apply to users. If you’re a WordPress developer it’s important that you code your own themes and plugins according to these criteria too. This will make your own sites more secure, fast and reliable, improve the service you provide to your clients and help you work as part of a development team.
In this post I’ll look at what makes quality code and give my top 10 tips for improving the quality of code in your themes and plugins, whether you’re coding for yourself, clients or for public release.
Aspects of “Quality” Code
There are a few main attributes of code which can be judged to be good quality, some of which relate to the way the code runs and some to the experience of users browsing a site built with that code. So what are these?
- Code that’s valid and standards-compliant.
- Code that conforms to the WordPress coding standards.
- Maintainable code that’s easy to build on.
- Correct use of WordPress APIs, functions, hooks, and classes.
- Accessible code that is inclusive and doesn’t discriminate against visitors using assistive technologies or with sensory impairments.
- Internationalization, so that users speaking languages other than your own can interact with your themes and plugins.
- Efficient code without unnecessary bloat.
- Logical code that you or others can understand and work with at a later date.
- Code that enhances the performance of a site running it.
- Code that doesn’t risk the security of sites running it.
Here I’ll examine what each of these means in detail and then give you 10 top tips to make sure your own code is high quality.
Valid, Standards-Compliant Code
The first rule of any code designed for use in a web browser is that it should be standards-compliant. If you haven’t already familiarized yourself with the W3C web standards, do so. Now.
Standards-compliant code will work as intended in modern browsers, including on mobile devices and with screen readers.
Some of the most important aspects of standards-compliant code are:
- Semantic code using HTML5 (if you aren’t using HTML5 yet, it’s worth noting that it works great with WordPress).
- Structuring your markup correctly, using the document tree according to the standards and making correct use of the
- Avoiding the use of unnecessary classes or IDs where possible.
- Using CSS and not HTML for presentation (which includes never using tables for layout).
- Ensuring images that are part of the content are coded in HTML and those that are decorative are coded in CSS.
- Cross-device and browser compatibility.
- Correct use of heading elements: don’t try to boost your SEO by putting headings in the wrong order, as a client of mine once attempted!
- Ensuring your code is accessible: more on this later in the post.
If you’re experimenting with new HTML and CSS features then this shouldn’t stop you doing that, especially in your own projects, but make sure they’re not essential to the flow of the page and that you provide a fallback. If your code is designed for release to the public I would advise against using these, however.
WordPress Coding Standards
The PHP standards include:
- Use of longhand PHP tags (i.e.
<?php ... ?>rather than
<? ... ?>).
- Use of single and double quotes.
- Indentation and braces.
- Use spaces after commas but remove them at the end of a line.
- Using functions to access the database.
- Naming conventions.
- Readability of code.
It’s also important to be aware of which functions, hooks and classes you should be using in your code and which ones are deprecated or incorrect.
If you’re not sure whether the code you’re using is correct or appropriate, simply check the latest coding standards in the Codex.
HTML standards include aspects of the W3C standards: if your code is standards-compliant, it should conform to the WordPress HTML standards.
The WordPress CSS standards include:
- Structure: make your stylesheets legible.
- Selectors: don’t over qualify them (e.g. use
div.container) and avoid underscores and capitals.
- Properties: group similar properties together.
- Syntax: use spaces, semicolons, and commas correctly.
- Media queries: use indentation and group them at the bottom of your stylesheets.
- Use spaces liberally for readability, including around elements and arguments.
- Long object declarations should be split across lines.
- Always use semicolons.
- Use indentation and line breaks for readability.
- Use braces and line breaks with
varto declare variables.
- Check the type of an object correctly.
switchstatements should be avoided in most cases, but coded correctly when necessary.
- Use arrays, objects and iteration correctly.
- Avoid ‘Yoda’s statements with incorrect ordering of elements within them.
Adhering to the coding standards will form the backbone of writing quality code for WordPress, but it isn’t everything. You need to augment this with the correct use of WordPress functions, hooks and classes among other things.
Correct Use of Functions, Hooks, and Classes
As well as writing your code in a way that complies with the WordPress coding standards, you also need to use the tools WordPress gives you correctly.
- Familiarise yourself with the WordPress APIs and use the relevant ones in your code
- Never hard code something when a WordPress function will do it for you. This includes using functions for links.
- Don’t use deprecated functions. If in doubt, check the Codex.
- Avoid functions like query_posts() which will slow your code down.
- Call scripts and libraries correctly, using a function (e.g.
wp_enqueue_script()) rather than a direct call.
- Call files correctly, using include and require functions in plugins and include tags in template files.
If your code is logical, valid and well structured (i.e. it meets the W3C and WordPress coding standards), that will go some way towards making it maintainable. But in WordPress there is more to this:
- Structure your themes correctly and logically, using extra template files only when needed.
- Avoid duplicated code in your theme template files by using template parts such as
- Use filters in your themes and plugins to allow users to alter or override your code without hacking the theme or plugin.
- Use hooks in your themes so that users can add extra content without having to hack the theme.
- Make sure you use themes for presentation and plugins for functionality – avoid the temptation to add lots of functionality to your themes.
Tim Berners-Lee, the inventor of the worldwide web, was emphatic about accessibility:
The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.
Accessibility is one of the central tenets of the W3C standards. If your code isn’t accessible for visitors using accessible technology, then it won’t validate.
If you want to better understand how to make your WordPress code accessible, then I recommend reading the Codex page on accessibility and also the Coolfields blog by Graham Armfield, who’s a WordPress accessibility expert.
You should also familiarise yourself with the Web Content Accessibility Guidelines (WCAG).
If you submit a theme to the WordPress plugin repository, it will be tested for accessibility: if a theme isn’t accessible it will be suspended from the repository. Criteria applied to themes comes under two headings: required and recommended. These apply to plugins just as much as themes and you should incorporate them into your plugins too.
1.6 million WordPress Superheroes read and trust our blog. Join them and get daily posts delivered to your inbox - free!
The required criteria include:
- Correct use of headings including the
h1element being used first.
- Use of ARIA roles.
- Code links correctly – use meaningful text in links (not ‘click here’) and ensure your links include titles.
- Use the correct elements for controls (
- Allow navigation with the keyboard, not just the mouse.
- Ensure contrast in your styling: backgrounds and foregrounds shouldn’t blend into each other.
- Include a ‘skip to content’ link on entering a page.
- Use correct markup for forms and make sure you use the
labelelement for each
- Code decorative images in CSS not HTML and always use an
altattribute for images included in your markup.
- Media such as video, audio or sliders shouldn’t auto-play without user input.
The recommended criteria are enabling zoomable text and avoiding using the same text for the
title attribute and the visible text.
Like accessibility, internationalisation (or i18n) is about inclusiveness: by internationalizing your code, you ensure that people who don’t speak the same language as you aren’t excluded from interacting with your themes and plugins.
i18n is about enabling translation of any text coded into your themes and plugins which the user can see and/or interact with. This will include descriptive text, headings and titles in your settings screens as well as any input fields or elements in your settings or in the theme customizer.
The W3C provides guidelines on internationalization. If your code is logical, valid and well structured (i.e. it meets the W3C and WordPress coding standards), that will go some way towards making it maintainable.
Efficient Code Without Unnecessary Bloat
Ensuring your code is efficient works in two ways: firstly, it will make the code easier to work with for you, your colleagues and users. Secondly it will make sites using your code faster. What’s not to like?
Here are some tips:
- Ensure your code is as tight as it can be while achieving what you need it to do.
- Avoid repetition of code: use an include file or write a function that you can use in multiple locations instead.
- Stick to the DRY (Don’t Repeat Yourself) principle.
- Use WordPress functions, hooks and classes correctly.
- Never write your own function when there’s a WordPress one that will do the same job.
- If you need to alter or override an existing function, try to use a filter where possible instead of a complete new function.
- In your themes, only use the template files you need.
- Keep functionality out of your themes – use a plugin instead.
- If you’re considering adding an extra feature to a theme or plugin, especially one which the user can activate or deactivate, consider whether it would be best including it in a separate plugin that the user activates only if they need it.
If in doubt, leave it out!
Logical Code That’s Easy to Work With
If other people (users, clients, or colleagues) will be working with your code, or if you will be working with it on a continuous basis (and this will happen even if you don’t expect it), then it’s important to make your code easy to work with and understand.
- Make liberal use of comments in your code to help you and other users understand what’s going on.
- When you’re calling include files, add comments so that users know what’s being called and where to find it and in the include file itself, add a note of which files call it.
- Structure your files logically, separating stylesheets, scripts and includes into separate folders in plugins.
- Use indentation and white space to make your code easy to scan.
- Include notes at the beginning of files to tell the user what’s happening in that file
- Structure your code logically: group like with like and include blocks of code in the order in which they’re used in your plugin and theme.
- Make use of include files but don’t overdo it so that people have to dig through multiple levels in the file structure before finding the code.
- Provide documentation for your code.
If you’re releasing your code to the public, documentation is essential. This is a requirement for the theme and plugin repository and should explain what your code does, how it’s structured and how to extend it.
Document the action and filter hooks in your plugin or theme so that people can make use of them, and provide information on the functions in your code and the structure of your files.
Performance-enhacning code: that sounds pretty impressive! Unfortunately it won’t help you run faster or live longer, but it will boost the performance of sites running your code.
If you’re coding plugins, this is less about enhancing performance (unless your plugin is one specifically designed to boost performance), and more about not slowing things down. Your themes should also take performance into account and be coded in a way that ensures pages in a site running your theme can be loaded as quickly as possible.
Ways to ensure your code doesn’t slow pages down include:
- Calling styles at the beginning of the page and scripts at the end, because of the order in which the browser requires them.
- Don’t hard code links: use the correct functions instead and they’ll be rendered correctly which means no redirects or errors.
- Avoid calling scripts and styles where they’re not needed.
- Use PHP to call correctly sized images in responsive sites instead of just resizing them using CSS. You can use the WordPress media size settings with featured images to do this.
- Never write a new function to do something WordPress already does.
- Call scripts correctly to avoid calling them multiple times.
- In plugins, use
include_once()where appropriate to avoid including or requiring files multiple times.
- Keep http requests to a minimum.
- Use CSS instead of images where possible for graphic effects.
- Take care with where you store data from your settings pages and use the database appropriately.
- Avoid running code that’s then overriden where possible.
- Avoid redirects unless absolutely essential.
If you follow these tips as well as the WordPress coding standards, your code will run faster which means the sites running it will be faster too.
Make sure you avoid bloat too, as this can slow down a site unnecessarily.
Last but by no means least, your code needs to be inherently secure and not make sites running it vulnerable to attack.
- Validate and sanitize data input to your settings screens using functions like
- Use nonces to ensure links can only be used as required.
- Monitor your code and update it quickly if you or your users discover any security issues.
- Avoid writing to files or directories from within your plugins unless absolutely necessary, and if it is needed make sure you do it in a way that’s secure.
- Avoid pulling in code from a third party source, especially executable code which is banned for plugins held in the plugin repository.
- Avoid obfuscated code.
- Don’t collect user data without permission.
Tips for Improving Your Code’s Quality
The headings above give a good idea of the main areas in which you can improve the quality of your WordPress code, which in turn will make your working life easier, make your clients and users happy and speed up the sites running your code.
There are a lot of pointers here, all of which are important if you want your code to be of a good enough quality to release it to the public or ship it to clients.
So here are my top 10 tips for ensuring your code is of high quality:
- Make sure your code is valid and standards-compliant.
- Conform to the WordPress coding standards.
- Make sure your code is accessible.
- Use WordPress functions, hooks and classes correctly, avoiding any that aren’t designed for themes plugins or are deprecated.
- Use a logical structure for your files and only use those files you need, for example limiting the template files in your themes.
- Stick to the DRY principle, using functions, classes and include files to avoid duplication of code.
- Internationalize your code.
- Avoid bloat: keep functionality out of themes and don’t include features most users will deactivate. Make sure your code is as efficient as possible.
- Ensure your code is secure.
- Provide documentation to help others understand your code and work with it.
If you follow these tips, you’ll write high quality code that is easy to work with, doesn’t cause any errors or performance issues and doesn’t clash with other themes and plugins.