Skip to content

Instantly share code, notes, and snippets.

@tormjens
Last active June 24, 2016 10:54
Show Gist options
  • Save tormjens/0ede85b25635ff8e692239ffec5df302 to your computer and use it in GitHub Desktop.
Save tormjens/0ede85b25635ff8e692239ffec5df302 to your computer and use it in GitHub Desktop.
WP Plugin Autoload

Autoloading for plugins

Say your plugin classes are following this naming convention My_Plugin_Thing and you name your files by the last "thing" e.g. thing.php inside the lib folder.

This snippet autoloads all classes within a the namespace. Handy!

Also, documentation poor. I'm tired!

<?php
define( 'PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'GITHUB_EXPLORER_URL', plugin_dir_url( __FILE__ ) );
function my_plugin_autoload($className) {
$segments = explode( '_', $className );
$name = strtolower( end( $segments ) );
$filename = PLUGIN_DIR . "lib/" . $name. ".php";
if (is_readable($filename)) {
require $filename;
}
}
spl_autoload_register('my_plugin_autoload');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment