WordPress 🤖 PHP Autoloader for themes and plugins

Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email
Share on twitter
Share on linkedin
Share on facebook
Share on whatsapp
Share on email

Here, I present a simple PHP function to load all PHP files contained in a folder of your theme WordPress.

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 );
                }
            }
        }
    }
}

Initializing and using the autoloader

To use this autoloader, simply call the function wprock_autoload() by passing as argument the path of the directory containing the PHP files to be loaded.

<?php
require_once get_template_directory() . '/inc/_autoloader.php';
wprock_autoload( get_stylesheet_directory(). '/inc/' );

Julien .MA Jacob
Developer WordPress
Julien MA Jacob - Developer WordPress
🧙♂️ Passionate about the web and programming with always lots of projects in mind 👨💻 | About page
  Discussion of the article
Subscribe to our newsletter
Notify of
guest
1 Commentary
most popular
latest oldest
Inline Feedbacks
View all comments
Mike

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

Why not use the autoloader to compose?