Skip to content

Instantly share code, notes, and snippets.

@sscovil
Last active December 20, 2015 08:09
Show Gist options
  • Save sscovil/6098665 to your computer and use it in GitHub Desktop.
Save sscovil/6098665 to your computer and use it in GitHub Desktop.
This class autoloader function eliminates the need to include_once every class file in your WordPress plugin. It adheres to WordPress file naming conventions, so instantiating a class named MyClass would attempt to include_once a file called inc/class-myclass.php.
<?php
/**
* Plugin Name: My Plugin
* Description: A sample plugin with class autoloader, for object-oriented programming.
* Version: 0.1
* Plugin URI: http://shaunscovil.com/
* Author: Shaun Scovil
* Author URI: http://shaunscovil.com/
* License: GPL2
*/
function my_class_autoloader( $classname ) {
$classfile = sprintf( '%sinc/class-%s.php',
plugin_dir_path( __FILE__ ),
str_replace( '_', '-', strtolower( $classname ) )
);
if ( file_exists( $classfile ) ) include_once( $classfile );
}
spl_autoload_register( 'my_class_autoloader' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment