arthur-eudeline
1/2/2019 - 2:09 PM

Autoloader PHP WordPress

<?php
/**
 * 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 );
          }
        }
      }
  }
}
<?php
require_once get_template_directory() . '/inc/_autoloader.php';
wprock_autoload( get_stylesheet_directory(). '/inc/' );