Approaching Modern WordPress Development: Part 1

It’s widely acknowledged that the WordPress codebase is difficult to work with. Many developers, myself included, find it overwhelming. Despite this, WordPress continues to surpass its competitors. Creating a user-friendly and robust CMS is a huge feat, and WordPress’s enduring popularity is a testament to its success in this area.

This begs the question: why should we be concerned about the code quality in WordPress core? After all, it functions as intended, doesn’t it?

Indeed, it does function, and it’s improbable that the 15-year-old codebase will undergo a complete overhaul by its volunteer maintainers. However, this implies that it serves as a model for coding “the WordPress way,” inadvertently justifying a lack of adherence to best practices and modern development techniques by countless developers. A multitude of WordPress plugins and themes are notorious for their substandard code, and blindly following outdated practices only perpetuates this issue.

But why should we be troubled by ineffective code that still performs its intended function? The truth is, there’s a hidden cost associated with subpar work. In the context of the WordPress codebase, the maintainers bear the cost in terms of their time, which is commendable. However, when it comes to your own code, it’s your client who ultimately pays the price.

For any system with even a moderate level of complexity, the initial development cost pales in comparison to the long-term maintenance cost, which includes adding new features. Employing a developer to rectify poorly designed and implemented software will cost significantly more than developing it correctly from the outset.

Inexpensive solutions almost always prove to be the most expensive in the long term, or they end up being abandoned due to budget constraints. Adhering to established software design principles and practices allows us to save clients money. These methods aren’t passing trends or changes for the sake of change. Their wisdom stems from the collective experience of developers, and following them yields tangible benefits.

Naturally, this doesn’t apply to truly basic tasks like adding a few lines of CSS or creating some custom posts and rewrites. However, simply combining a few plugins (or more often, a multitude of plugins) or churning out a Visual Composer-powered site doesn’t qualify as software engineering.

This isn’t inherently negative. In fact, the simplicity of some solutions is precisely why WordPress is so popular. Nevertheless, in this series, I’ll be discussing real WordPress development: writing substantial PHP, HTML, CSS, and JavaScript code. I’ll begin with the overall workflow and then delve into WordPress front-end development in this article.

Modern WordPress Development Workflow

In general, high-quality code exhibits the following characteristics:

  • Readability: Understanding the code’s purpose and functionality is straightforward.
  • Modularity: Small code blocks with a well-defined purpose are easy to comprehend, develop, and test.
  • Reusability: Re-utilizing previously developed modules for tackling similar problems considerably accelerates development.
  • Maintainability: Modifying existing functionality or introducing new features is straightforward.

The primary advantages—reduced development and ownership costs—lead to numerous other benefits that I won’t delve into here.

Instead, I’ll concentrate on the specific development techniques and best practices that can aid you in producing high-quality code. Let’s start with version control.

Use Version Control

This translates to using Git. Regrettably, “cowboy coding” on production servers via FTP is still surprisingly prevalent. I recently worked with a UK-based agency where their codebase was littered with files like these:

  • functions copy.php
  • functions copy 2.php
  • functions test.php
  • functions2.php
  • functions test2.php

When taking over a WordPress site, the very first step should be to place it under version control. Tanking Servers offers an entertaining look back at common WordPress development blunders. Using Git would have made it incredibly easy to rectify those errors—and similar mishaps that most developers have likely encountered.

Did a coding error bring down the entire site? git reset restores everything to its previous state. Did a new version update wreak havoc? git reset acts as a time machine. Did malicious code mysteriously appear? git status reveals any new, deleted, or modified tracked files. A simple git checkout then restores the originals.

Beware of Exposing the .git Folder

Using Git is undeniably crucial. However, when you do, it’s equally important to avoid exposing your Git repository to being hacked. The issue arises when your .git folders are publicly accessible and contain stored credentials.

A standard WordPress installation resides entirely within a public web folder, making it highly probable that the .git folder is also located there. While login credentials should never be stored in the Git repository, many repositories do contain sensitive information that shouldn’t be publicly accessible.

Therefore, public access to the .git folder should be restricted. If you’re using Apache, adding the code snippet below at the beginning of your .htaccess file will block access to both the .git folder and the log files. Log files frequently contain sensitive information, so it’s prudent to restrict access to them as well. For other web server configurations, it’s best to seek assistance from your DevOps expert.

1
2
RedirectMatch 404 /\.git
RedirectMatch 404 ^.*\.log

Use Separate Environments

Never conduct development on live sites—it’s a surefire way to cause downtime and unhappy clients. So, how should you set things up?

Ideally, you should have three separate development environments, with code always flowing in a single direction: local → staging → production. This proven method effectively prevents conflicts. All core, plugin, and theme updates are implemented locally first, then tested in the staging environment, and finally deployed to the production environment.

For instance, server-specific configurations could be stored in a separate file. You can create a wp-config-local.php file for each local and staging environment. (Don’t forget to add it to your .gitignore file!) Then, insert the following code snippet into your wp-config.php file:

1
2
3
4
5
6
if (file_exists(dirname(__FILE__) . '/wp-config-local.php')) :
  // use local settings
  require_once(dirname(__FILE__) . '/wp-config-local.php');
else :
  // production settings
endif;

Environment variables are often the most efficient way to set up different environments. If you’re unfamiliar with this concept, I recommend exploring a comprehensive modern solution like Roots.

Use WP-CLI

The WordPress command-line interface (WP-CLI) is an incredibly valuable tool for managing WordPress installations. Having access to WP-CLI empowers you to execute virtually any WordPress API function. For example, you can add, delete, and modify users and their passwords using WP-CLI. This is particularly useful if you inherit a site where the owner has locked themselves out.

As another example, initial deployments become effortless with WP-CLI. These tasks can be accomplished with just a few commands:

  • Downloading core files, themes, and plugins
  • Performing database search and replace operations
  • Adding an administrator user

Moreover, these actions can be scripted and automated.

Use Advanced Deployment Options

Speaking of automation, familiarizing yourself with deployment technologies and processes such as:

is worthwhile.

Admittedly, transitioning from not using version control to working with Docker is a significant leap and will likely be overwhelming for a typical solo WordPress project. Furthermore, some options might not be feasible depending on your hosting provider. However, advanced deployment is essential for teams and larger projects.

Use Linting

For projects of any scale, linting proves beneficial to most developers. Linting involves automatically scanning your code for errors. While full-featured IDEs like PHPStorm offer this functionality out of the box, simpler editors like VSCode or Sublime Text require a dedicated program known as a linter. One way to set this up is to configure your editor to run a linter every time you save a file.

PHP_CodeSniffer is the industry-standard linter for PHP. In addition to identifying syntax errors, it can also verify if your code adheres to style guidelines like PSR-2, making it much easier to follow coding standards.

For JavaScript, ESLint is a popular linter. It boasts a comprehensive ruleset and supports custom configurations for various JavaScript flavors and frameworks.

A particularly powerful application of linting is incorporating it into a CI/CD pipeline, which ensures that all code is automatically validated before deployment.

Modern WordPress Front-end Development Techniques

Now that we’ve established a robust workflow for your overall WordPress project, let’s delve into best practices for front-end development.

Use Modern Tooling: Sass and ES6+

The front-end development landscape is constantly evolving. While we once considered Sass the ultimate tool for writing CSS—and it remains relevant for pre-Gutenberg WordPress development—the focus has shifted to CSS-in-JS and styled components.

Even WordPress couldn’t resist adopting some of these new technologies. Gutenberg, the new block editor, is built on React and a REST API.

You should make it a priority to familiarize yourself with these fundamental front-end technologies:

ES6 and Sass are essentially modern JavaScript and CSS, respectively, while Webpack is a tool that facilitates the use of all these modern features without the worry of backward compatibility issues. Think of Webpack as a front-end application compiler that generates files suitable for browser use.

Transition from jQuery to Vue.js or React

Given that the WordPress core and nearly all WordPress plugins rely on jQuery, you can’t completely abandon it. In fact, it makes little sense to stop using it for simple tasks like hiding a few <div> elements or making a one-time AJAX request, especially if you’re accustomed to doing so. jQuery will be loaded anyway, and it’s undeniably straightforward to use.

However, jQuery struggles with complex applications due to its difficult-to-follow logic, callback hell, global variables, and lack of HTML templating. This clearly necessitates a different approach to organizing your front-end application.

Modern front-end libraries like React leverage object-oriented programming (OOP) principles and structure front-end application architecture into modular, reusable components. A component encapsulates all the code, markup, and “component state” (variables) for a specific element. An element can be virtually anything: a button, input field, user form, or even a widget that fetches and displays recent posts from the WordPress REST API back end. Components can contain other components, creating a hierarchical structure.

Given the intricate nature of modern web pages, organizing an application into components has proven to be an effective method for building maintainable, high-performance web applications of any scale. Components are highly reusable, isolated, and therefore easily testable “building blocks,” making it worthwhile to invest time in learning this concept.

Currently, two component-based libraries are gaining significant traction: Vue.js and React. While React might seem like the obvious choice given its use in Gutenberg, Vue.js could be a more beginner-friendly option for those new to modern JavaScript.

React immerses you directly into the deep end by utilizing ES6 features, classes, proprietary JSX syntax, and a Webpack build pipeline from the get-go, resulting in a steep learning curve.

Vue.js, on the other hand, is considerably more approachable and can be used by just dropping in a <script> tag. It utilizes plain JavaScript (ES5), HTML, and CSS, introducing new concepts gradually.

Once you’ve tackled a few Vue.js projects, you’ll be better equipped to dive into the complexities of React. Although not always necessary, React is a prerequisite for Gutenberg development.

Use the WordPress REST API

The WordPress REST API is essentially a standardized interface for remotely requesting and modifying data from WordPress. It’s more of a software architecture concept than a completely different coding paradigm. You can still use the same old jQuery AJAX snippets with slightly modified parameters.

What’s the most significant benefit? Since the WordPress REST API standardizes communication between the back end and front end, it represents a significant step towards modularity, reusability, and readability in your code. Those dreaded templates with intermingled HTML, PHP, and even SQL snippets need to be phased out. Once templates consist solely of HTML with placeholders for data passed as parameters, there’s no substantial difference between passing that data in PHP or via a REST API to a front-end application.

You might also want to explore WPGraphQL. While it’s uncertain whether it will eventually supersede the WordPress REST API, it’s rapidly gaining popularity.

Learn Gutenberg (Clients Will Require It Soon)

The ultimate objective of Gutenberg is complete site customization, among other plans.

This lays the groundwork for a new model for WordPress Core that will ultimately impact the entire publishing experience of the platform.

The WordPress Gutenberg project page on GitHub

Gutenberg faced significant opposition from WordPress developers. Some of the arguments against merging it into WordPress core included:

  • A considerable portion of end-users don’t require it, suggesting it should be an optional plugin rather than part of the core
  • It caused issues with some existing sites
  • It wasn’t deemed ready for prime time and could benefit from further refinement and bug fixes

However, for content creators who utilize WordPress primarily as a blogging platform, Gutenberg undoubtedly offers a superior experience compared to the old editor.

While disabling Gutenberg will remain an option for as long as necessary, familiarizing yourself with it now is a wise decision. When a client approaches you with a Gutenberg development request, you’ll be fully prepared.

Time to Get Up to Speed: Even the “WordPress Way” Is Evolving

The most frequent argument against utilizing all the tools and techniques discussed above in WordPress development is that the “WordPress way” of doing things remains effective, implying that it’s inherently superior to all these new and shiny tools.

However, as we’ve seen, the WordPress core developers are acutely aware of all the latest advancements. Moreover, they actively incorporate them into newer parts of the core whenever possible due to their clear advantages. The only limiting factor is the legacy code that’s unlikely to be refactored.

For some time now, WordPress and WooCommerce have adopted the practice of developing “feature plugins” that implement and utilize new technologies. When deemed ready, these plugins are merged into the core, as was the case with Gutenberg. WooCommerce also has its own dedicated React project. Similarly, the WordPress REST API began as a separate plugin and is now an integral part of the WordPress core.

The question isn’t if we should learn new things and incorporate them into our daily work, but rather how. The answer is “incrementally,” one step at a time. Focus on learning something new or accomplishing a familiar task using a new and different approach.

For instance, learn how to integrate Webpack with your existing scripts. Webpack can transpile your new ES6+ code into “plain” JavaScript that’s compatible with older browsers. It can also minify and bundle scripts. That’s one new thing learned. Once you’ve mastered that, rewrite your JavaScript code by leveraging ES6 features. This represents a new way of accomplishing a familiar task.

The outcome: You’ll have gained proficiency in both Webpack and ES6. As professionals, it’s our responsibility to continuously progress and expand our knowledge. And when we do, it’s essential to share that knowledge. Toptal maintains a list of WordPress development best practices and welcomes community contributions to it.

In Part 2 of this series, we’ll delve into the PHP aspects of modern WordPress back-end development.

Licensed under CC BY-NC-SA 4.0