Skip to content

Instantly share code, notes, and snippets.

@Rarst
Created February 27, 2013 17:47
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Rarst/5049915 to your computer and use it in GitHub Desktop.
Save Rarst/5049915 to your computer and use it in GitHub Desktop.
Generic autoloader for classes named in WordPress coding style.
<?php
if ( ! class_exists( 'Autoload_WP' ) ) {
/**
* Generic autoloader for classes named in WordPress coding style.
*/
class Autoload_WP {
public $dir = __DIR__;
function __construct( $dir = '' ) {
if ( ! empty( $dir ) )
$this->dir = $dir;
spl_autoload_register( array( $this, 'spl_autoload_register' ) );
}
function spl_autoload_register( $class_name ) {
$class_path = $this->dir . '/class-' . strtolower( str_replace( '_', '-', $class_name ) ) . '.php';
if ( file_exists( $class_path ) )
include $class_path;
}
}
}
@rutwick
Copy link

rutwick commented Jul 17, 2015

Changing the original comment since I found out what was wrong.

This autoloader didn't work for a class which was in a sub folder of my plugin. It ends up appending the 'class' term to the sub folder name and not the actual class file.

@lfbn
Copy link

lfbn commented Apr 4, 2016

You can append the sub folder name that you need in the constructor, to the dir property. And choosing to have your own autoloading class with a different name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment