Working with errors in WordPress development

Debugging and preventing WordPress errors isn't as straight forward as it should be, here's some tips and tricks to help streamline the process!

By Luke Whitehouse on

PHPWordPress

Article

PHP warnings, MySQL connection problems and undeclared JavaScript variables, just some of the various challenges we must overcome on any given project. Debugging errors in web development is a natural stepping stone on the road to our finished product and something we must learn to control if we are to prevent them from leaking into our live websites.

When working with WordPress, debugging isn't straight forward. Hell, with a codebase of over 14 years it's no wonder. So, how can we utilise the tools WordPress provides, and our own knowledge of PHP best practices to create a workflow allowing for efficient and controlled debugging throughout our applications?

"Good questions, Luke." - You.

Namespacing

First things first, we want to overcome the lack of namespacing in WordPress. If you're wondering what that is, then I'll let Google engineer Addy Osmani explain it from his blog post on Essential JavaScript Namespacing Patterns.

In many programming languages, namespacing is a technique employed to avoid collisions with other objects or variables in the global namespace. They're also extremely useful for helping organize blocks of functionality in your application into easily manageable groups that can be uniquely identified.

Addy Osmani - Essential JavaScript Namespacing Patterns

Addy touches on this concept of the global namespace, which refers to the current 'scope' of your application, or rather, what's accessible to what, at which points. As an example, take the following functions.

/**
*	app.php
*/

/**
* Get name from database
*/
function myName() {
  // Pretend we're getting this from a database
  $name = 'Luke';

  return $name;
}

/**
* Create a customised welcome message based on user's name
*/
function welcomeMessage($name) {
  return 'Hello, ' . $name . ', and welcome to the rest of your life!';
}

These two functions work in tandem, so to call them we'd do something like...

$me = myName();
echo welcomeMessage($me);

If we wanted to, we could grab that snippet and add it to our website. However, what if we already had a function called myName() or we didn't want the contents of $me to be accessible to other areas of our website? Perhaps the variable contains sensitive information? This is where scope comes into play. Setting certain pieces of our code to be scoped to a particular area ensures they're only accessible from that place.

At that point it's worth mentioning that the concept of 'Scope' in Software Development is a much bigger topic than what I'd like to get into in this post. If you're interested, I'd recommend this Stack Overflow thread as a good starting point to learn more.

Unfortunately, WordPress uses the global scope rather than any form of namespacing. Whilst we cannot tackle the problem of functions being accessible globally in our website, we can tackle naming conflicts.

So let's set the scene.

If we were to create a new function called get_the_title() then you'd get an error as this would conflict with the get_the_title() function that comes with WordPress. This can be a major problem when it comes to third-party themes and plugins where you don't know what functions and variables have already been created.

To combat this, we can prefix our functions and variables. It doesn't matter what your prefix is, but I'd recommend it be something specific to your website. You'll notice in a lot of my WordPress tutorials I like to use the prefix of asrt (short for Assortment), so my new function would be asrt_get_the_title().

Prefixing your code will also allow for easy detection of code you've wrote further down the line through the use of find and replace filters in your code editor and is considered a best practice in WordPress development so get used to it, you'll thank me later!

On the topic of third-party code...

Limiting third-party code

Whenever you add third-party code into your project you're introducing risk and fragility. To stay on top of these risks you'll need to be asking yourself various questions throughout your project's lifespan:

  • Is the code actively maintained? What's the likelihood of that changing in a year's time? If that ever becomes the case, you run the risk of errors from incompatible code with newer versions of WordPress or similar.
  • Is the third-party code well structured? Have you actually looked at what it's doing behind the scenes? Bad code is obviously a no-no. Depending on the context, this could have various performance, security or stability problems. Probably a mixture of them all.
  • Does this conflict with any of my code or existing third-party software in use? If so, you'll need to factor in the time you'll spend making the necessary changes.

Before you download that plugin or toy around with that new boilerplate theme, ask yourself if you actually need them. Is it absolutely required or can you live without it? Is it something you could create yourself, perhaps even better? If it's just a plugin that sets up a jQuery slider, consider doing it yourself.

Don't get me wrong, there are definitely benefits to using third-party packages or the concept wouldn't exist in the first place, but those benefits have to be weighed up against the cons. It's about performing the due diligence to ensure the third-party code you've introduced is worth it.

Let's assume you've found a really cool plugin that you would like to add to your project. First things first, we need to check over it's compatibility and life expectancy. If a plugin is published on the official plugins directory then you'll have all the information you need to get started.

Fig 1: Yoast SEO plugin page on wordpress.org
Fig 1: Yoast SEO plugin page on wordpress.org

Scroll down the page and in the sidebar you'll see some key information about the plugin.

Fig 2: Key information for the Yoast SEO plugin
Fig 2: Key information for the Yoast SEO plugin

Taking Yoast SEO as an example, I can see that at present this plugin:

  • Requires WordPress to be at version 4.6 or higher;
  • is compatible with 4.7.3;
  • and is very active, seeing as it was last updated 2 days ago.

If the plugin hadn't been updated since 2016 then that would tell me that the plugin is potentially no longer receiving updates. If compatibility didn't mention the current version of WordPress that would also tell me that it hasn't been tested yet.

Once you've approved and tested (more on this later) that the plugin is good-to-go, then I'd recommend creating a document of all approved third-party code you are willing to use in your projects. If you're working with multiple people or having to come back onto a project in a years time, this will ensure everyone is on the same page moving forward.

WordPress updates

Keep it up to date! Nothing more to say, just do it. Nearly every update has some form of security update or bug to patch so it's a good idea for your client websites and any other websites you may host.

Before you update though, ensure you've checked that any third-party code you have installed is compatible with that version. If not, you may need to wait a few days or even weeks before continuing.

Finally, I'd always recommend updating locally first rather than on your live website just incase there is anything you may have missed. That leads me nicely onto deployment.

Deployment environment

In most branches of software development we have the concept of environments on which we're working with our product. At the very least you'll have your live website, or as it's also known, the production environment. Your production environment is what your users see, so it's essential to keep this bug free and in tip-top condition, which is where your other environments come in handy.

When developing your website you should never do this on the production environment, as any changes (bugs or otherwise) would be seen by all. Instead, you would recreate the website locally, known as your local environment. Where possible, this should mimic the same specifications of your live website (such as PHP versions, extensions, web server) as any differences to either could make you miss an error that slips its way into the production environment.

I would also recommend setting up an additional server exactly the same as your production server to test your work in progress development. This is known as a staging server. Whilst a local environment will pick up 99% of problems, it's never going to be an exact match to a live working server environment that you have your live website sit on, this is where the staging server helps.

Of course, you could go as far as you'd like with this concept, having multiple staging servers with slightly different specifications to test the compatibility of your website, but as a starter, I'd recommend this 'local, staging and production' setup, which should work great for small to medium sized projects.

Debugging

Throughout the development of your website you'll want to know when an error occurs from something you wrote. Luckily WordPress' debugging tools can help with this. Whilst they're by no means the best, they do get the job done with a little help.

Within the default wp-config.php found at the root of your WordPress installation you'll find the line define('WP_DEBUG', false);. Changing the false to true will enable WordPress' debugging tools and cause all PHP errors, notices and warnings to be displayed, which will help pick up on any broken functionality or code which does not follow proper data validation conventions inside PHP.

In addition, as WordPress is based on PHP, you could also use the error log file for PHP, the location of which depends on your web server. For most web servers, this can be found in /var/log/apache2 but for server environment tools such as MAMP it may differ.

Once you've opened this file, every time an error occurs on your website it will show as a new entry in this file. The benefit of this over WP_DEBUG is that you have one unified place for errors to appear, whereas with WP_DEBUG errors could appear anywhere on the page.

Error monitoring

No matter how much protection you put in place, there's always going to be the chance that errors make their way into your live website. You may also find that as you update your website and server you find new errors pop up as a result and for those reasons it's good to have ways of tracking them and being alerted as soon as they appear.

There are so many tools for this it's crazy but I'd recommend taking a look at:

  • New Relic
  • Pingdom
  • Rapidspike

There's a lot to discuss with error monitoring so I'll follow this post up in the future with a guide on setting those tools up.

I've jumped around quite a few important topics but hopefully this givens you enough to move forward with in your next project.

Until next time 

Follow us on Twitter, Facebook or Github.
© Copyright 2021 Assortment.
Created and maintained by Luke Whitehouse.