Skip to content

Autoloading in your wordpress plugin

Autoloading in your wordpress plugin

An important thing to note is that you will want your autoloader to load classes from your plugin only. If you do not enforce this restriction, your plugin may end up conflicting with WordPress or other plugins.

To enforce this restriction, simply check the classNamevariable in the autoload function for your plugin’s namespace. An example is shown below

if(strpos($className, __NAMESPACE__) !== 0)
        return;

So a simple autoloader would look like this (replace PLUGIN_PATH_HERE with your plugin’s path)

spl_autoload_register(__NAMESPACE__ . '\\autoload');
function autoload($className)
{
    $ext = '.php';
    $cls = ltrim($className, '\\');
    if(strpos($className, __NAMESPACE__) !== 0)
        return;

    $cls = str_replace(__NAMESPACE__, '', $className);
    $path = PLUGIN_PATH_HERE . str_replace('\\', DIRECTORY_SEPARATOR, $className) . $ext; // Replace PLUGIN_PATH_HERE with your plugin path
    require_once($path);
}

 

Enjoyed the content ? Share it with your friends !
Published inDevelopment

Be First to Comment

Leave a Reply

Your email address will not be published.