Adding wordpress autoload to plugin boilerplate

The wordpress plugin boilerplate generator is a great site for creating a starting point of a new wordpress plugin, but by default when you generate the code there is no autoload included so as you add new classes you also have to add their file into the loader class. This post shows how to add a wordpress autoload method so your new classes are loaded ‘on-the-fly’.

The normal method which is responsible for loading the classes is the load_dependencies() method in the main plugin class and this is shown below from a module I’m creating called TaxonomyBrowser. As you can see the class files are loaded by individual require_once statements for each of the different class names.

To add wordpress autoload functionality I change the method to look like this:

So the first thing this does is register an autoload function as a local method and then removes all the individual require_once calls. The autoload function is shown in the code below the load_dependencies method.

The autoload function will be called with any class names which the system can’t find and it is responsible for making sure the correct class file is required.

The first part of the autoload converts the class name into the file name which holds the class. The code which goes here will depend on the convention you have adopted to name your class files. In this example, the convention is to put classes into a file called ‘class-xxxx.php’ where xxxx is the class name with underscores converted to hyphens. This is the convention which the wordpress boilerplate code generator uses.

With the filename sorted, we need to create the list of directories the class could be in. For this boilerplate framework, the directories are either ‘includes’, ‘admin’ or ‘public’. Since the file that this code lives in is in the includes directory we take advantage of that by finding the directory the file is in with

realpath( plugin_dir_path( __FILE__ ) );

and then use str_replace to change the ‘includes’ to admin and public to get all the possible directories.

Then it’s just a question of looping through each of the possible directories and finding if the requested class file exists – if it does we include it with a requires-once and return.

The advantage of making this change is that as new class files are added to the project, they are automatically found and included and don’t need to be manually added.

The only time you would need to make more changes is if you add new directories where class files are located – in that case you just add those directories into the autoloader and they will be automatically found.

Leave a Reply