Skip to content
Advertisement

Why is my autoloader loading every class in my wp install?

Ive been working on a wordpress plugin and Ive had to extend a class in another file, something I’ve not done before. So this has got me into using an autoloader. To give you some idea of my folder structure.

My plugin directory

plugins/knp-vendor-portal/

My folder structure.

/knp-classes

/css

/js

knp-vendor-portal.php

In my main plugin file Im using the following to load my classes, however when I look in the query monitor I get a tonne of errors. The errors state the the include_once function seems to be trying to load hundreds more classes from all the other plugins. So why doesnt it only load the classes from my plugin if the DIR name is pointing at my classes directory.

Here is the code Im using in my main plugin file.

function knp_load_first(){

    //Auto load all the class files
    spl_autoload_register('knpv_autoloader');

   //Some other code calling some methods


}
add_action('plugins_loaded', 'knp_load_first');

function knpv_autoloader($classname){

    include_once plugin_dir_path( __FILE__ ).'knp-classes/'.$classname.'.php';

}

Advertisement

Answer

The autoloader runs for every class which isn’t already loaded when it’s tried to load. You need to check the $classname in the knpv_autoloader function matches your namespace or naming convention before attempting to load it from the knp-classes directory. For example…

function knpv_autoloader($classname)
{
    if (strpos($classname, 'knpv_') !== false) {
        include_once plugin_dir_path( __FILE__ ).'knp-classes/'.$classname.'.php';
    }
}

This assumes that your classes have the prefix knpv_, if you’re using a namespace you could check for that too something like Knpv\ etc…

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement