Simple WordPress Autoloader

WordPressPosted on

If we develop a bit more complex theme or plugin where we want to use the modern PHP concepts, probably we want to use a simple autoloader for that. This snippet provides a starting point how could a basic WordPress compatible loader looks like. Replace the paths and the namespaces and you are ready to go!

// The autoloader takes care of automatic file loading.
// If the given class has the namespace we want, and
// the file exists we include it automatically.
spl_autoload_register(function ($class) {
    if (strpos($class, 'Your\\Namespace\\') !== 0) {
        return;
    }

    $file = __DIR__ . sprintf('/your/files/%s.php', str_replace(['Your\\Namespace\\', '\\'], ['', '/'], $class));
    
    if (file_exists($file)) {
        require_once $file;
    }
});

Need a web developer? Maybe we can help, get in touch!

Looking for web dev job?
You can check them on Jooble.

To see and write comments, you must allow the related (Disqus) cookies. For more information, please visit our privacy policy page.

Similar Posts

More content in WordPress category