My WordPress Plugin Class Autoloader

Here’s one that many people are likely using a variation of the same functionality, but useful nonetheless. This is the autoloader that I use in most of the plugins that I create.

Edit: as pointed out by Francis Santerre on the Advanced WordPress group on Facebook, this snippet does not follow WordPress standards when it comes to file naming conventions. Personally, I’m not a fan of using the “class-” keyword to preface my class files as it would cause nearly every file to include it (and it doesn’t really affect code quality or WordPress plugin repo submissions), but it’s certainly worth mentioning. Francis has also included a link to his autoloader that he uses on his projects.

My autoloader:

<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

function example_autoload( $classname ) {
    $class     = str_replace( '\\', DIRECTORY_SEPARATOR, str_replace( '_', '-', strtolower($classname) ) );
    $file_path = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $class . '.php';
    if ( file_exists( $file_path ) ) {
        require_once $file_path;
    }
}

spl_autoload_register('example_autoload');

To use this, drop it somewhere within your plugin. Usually, I include this within its own file and require it at the beginning of the main plugin file.

For your classes to utilize it correctly, your namespaces should look something like this:

// Filename: wp-content/plugins/example-plugin/class-name.php
namespace Example_Plugin\Class_Name;

Why autoloaders? It saves a hell of a lot of work in using require_once everywhere. Instead of manually requiring all the files you need, you can simply include the autoloader once, and call the namespaced classes that you need.

Have a snippet to share?

Submit your snippet!

2 comments

Leave a Reply