Skip to content

Instantly share code, notes, and snippets.

@harryfinn
Last active May 9, 2017 15:16
Show Gist options
  • Save harryfinn/3b3deff746417797311e to your computer and use it in GitHub Desktop.
Save harryfinn/3b3deff746417797311e to your computer and use it in GitHub Desktop.
WordPress autoloader for PHP Classes

WordPress PHP Class autoloader

The issue

I recently came across an issue whereby installing the popular Yoast SEO plugin caused the frontend of a production site to crash, stating that it couldn't find many of the custom PHP classes written and included in the project theme via the __autoload() php function.

I found others had experienced similar issues when trying to use Yoast with custom PHP classes but not found a fix. Although this issue was also known to the Yoast plugin authors, a fix had yet to appear, so I started to try to find/create a fix myself.

The Fix

It turns out that the way in which WP tries to handle autoloading from theme and plugin classes can cause a confliction when the wrapper function is told to load to early on, sometimes (in the case of Yoast SEO), resulting in a loading conflict where neither class is then loaded properly.

The code in the functions.php file is a way around this as the __autoload method can only be defined/called once, whereas spl_autoload_register adds methods to the autoload queue and prevents this conflict issue!

<?php
function autoload_classes($name) {
$class_path = get_template_directory() . '/includes/class.' . strtolower($name) . '.php';
if(file_exists($class_path)) {
require_once $class_path;
}
}
spl_autoload_register('autoload_classes');
if(function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment