One of the biggest tips I’d give to any new programmers is that your code should gracefully degrade. Let’s look at a simplified example in a recent WordPress project I was working on.
In a plugin there was a line similar to what you’d see below that includes a file from a theme.
require_once plugin_dir_path(__FILE__) . '../../themes/<theme-name>/lib/assets.php';
In our default install this isn’t a problem because the theme exists and assets.php
also exists. So the file is included and we have no issues.
But this week I’ve been building a system to check which theme is active and force activate a specific theme for a site if it’s not active. It also lets us know if the theme isn’t present so it can’t be activated. While testing this I renamed the theme folder to have it deactivate itself and then the line above breaks.
This is where we should fail gracefully and check if we have the file in the expected location before we try and include it. Further, outside of standard PHP notices, there is no reporting at any level about the issue.
I’ve added a task to fix this, but this is what the fix would look like in pseudo-code if you’re curious.
- Check if the theme exists with
wp_get_themes()
[^1] - If theme exists, check if the file in question exists
- If either of the above fail, let someone know about it in your reporting system so that the issue can be resolved.
In the case above, I’d send a message to the our dev
slack channel along with some information about what the fix should be and if a developer should be involved. We have a number of errors that can be handled by support staff without involving a developer because of the tooling we’ve already built.
In general, before you try to use some custom functionality, make sure it exists and then deal with the case if it doesn’t exist so your whole site doesn’t die.
Yes we should not even have a plugin/theme dependency like this. That is a different topic to address and one of the many items of technical debt we need to dig out of.
[^1]: This can be an expensive function so be clear about it’s cost and that the cost of the function increases as you add more themes.