Recently I’ve been tasked with integrating a few API’s into WordPress sites. Whilst this doesn’t seem too hard, I found it hard to find solid documentation on the best practices in this scenario.
In this post I will explain how I decided to go about these integrations, focussing mainly on my class loading inside WordPress.
Themes in WordPress all seem to be very procedural. This is fine for a little theme, but as soon as you start making a few changes, that
functions.php file becomes unwieldy pretty quick. I’ve seen people split up their functions files into separate files, each holding functions for a certain part of the site. That’s not bad, but then you’ve got to make sure you
include them all into your
functions.php file which looks horrendous!
By structuring your code properly, you can move your function calls into classes, these classes can then be autoloaded using PHP’s spl_autoload_register function. Autoloading means no more including files, as long as your register function knows where to look for the code, it will include is for you. Doesn’t that sound good?
How it’s done
Rather than write my own autoloader, I opted to use the Class Example autoloader, defined by the php-fig, which is available here. I add this file, as
autoloader.php to my theme root, this is then included into the top of the
In the demo below, I have a folder called
Services that holds all of my API classes, these classes are then in turn contained within the
services namespace. On line
16 I am passing this namespace into the autoloader and then telling it the location of these classes. Remember, as they are in the theme directory, we need to prefix the folder with the theme directory location, hence the use of the
You can call the
addNamespace method as many times as you like with different namespaces and directories, if your classes are split up a little more.
Now we’ve registered our autoloader we can call classes as and when we need them without having to worry about including the file each time, whether that be from the
functions.php file or from inside a template, it doesn’t really matter as they’re always available. You will however have to call the class with it’s full namespace or make use of the use statement in PHP to import that namespace.
If you’d like to know more about namespacing and autoloading classes, there are some great resources below: