Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

WordPress Class Autoloader


PHP, WordPress
David Egan

Assuming that classes have been saved in individual files, according to WordPress best practice guidelines: The file /classes/my-unique-class.php contains My_Unique_Class().

function my_class_autoloader( $classname ) {

  // Build a filename that matches the correct protocol
  ------------------------------------------------------------------------------
  $classfile = sprintf( '%s/classes/class-%s.php',
  get_template_directory(),
  str_replace( '_', '-', strtolower( $classname ) )
  );

  if ( file_exists( $classfile ) ) include_once( $classfile );

}

// This function "creates a queue of autoload functions, and runs through each of them in the order they are defined."
// -----------------------------------------------------------------------------
spl_autoload_register( 'my_class_autoloader' );

comments powered by Disqus