WordPress 🤖 PHP Autoloader for themes and plugins

Share on email
Share on twitter
Share on linkedin
Share on facebook
Illustration: source code, sublime text
Illustration: source code, sublime text
Illustration: source code, sublime text
Illustration: source code, sublime text
Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email

Here, I present you with a simple PHP function to load all the PHP files contained in a folder of your WordPress themes.

Autoloader code

/**
 * Use require_once on all PHP files in a path.
 * No load file "index.php" and files who start with "_"
 * @param  string/array() $path Directory or array of directories to use for load files
 */
function wprock_autoload( $paths = array() ) {
    if ( empty( $paths ) ) {
        return;
    }
    if ( is_string( $paths ) ) {
        $paths = array( $paths );
    }
    foreach ( $paths as $path ) {
        if ( is_dir( $path ) ) {
            $files = scandir( $path );
            foreach ( $files as $file ) {
                if (
                    ( '.php' === substr( $file, -4) )   // End with '.php'
                    && ( '_' !== substr( $file, 0, 1) ) // Don't start with '_'
                    && ( 'index.php' !== $file )       // Is not index.php file
                ) {
                    require_once( $path . $file );
                }
            }
        }
    }
}

Initialize and use the autoloader

To use this autoloader, simply call the function wprock_autoload() by passing as an argument the path of the folder that contains the PHP files to load.

Julien MA Jacob
WordPress Developer
Julien MA JACOB - WordPress Developer
Passionate about the web and programming with always many projects in mind
  Discussion of the article
Subscribe to the newsletter
Notify to
guest
1 Commentary
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mike

Why didn't you just use the PHP spl_autoload_register function?

Why not use the autoloader to dial?