Last active
April 17, 2018 21:52
-
-
Save chaance/601c248904ee022b8609f0dce6f561c9 to your computer and use it in GitHub Desktop.
wp-class-autoloader
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( ! defined( 'WPINC' ) ) { | |
die; | |
} | |
/** | |
* Class autoloader | |
* | |
* @param string $class Qualified class name. | |
*/ | |
function xx_class_autoloader( $class ) { | |
// If the $class_name does not include our theme's namespace, GTFO. | |
if ( false === strpos( $class, 'Theme_Name' ) ) { | |
return; | |
} | |
$namespace_parts = explode( '\\', $class ); | |
// Format parts to match filenames. | |
$file_parts = array_map( function( $part ) { | |
return str_replace( '_', '-', strtolower( $part ) ); | |
}, $namespace_parts ); | |
$class_path = get_template_directory() . '/inc/classes/'; | |
// If class uses sub-namespaces, we'll stick them in matching sub-directories. | |
if ( count( $file_parts ) > 2 ) { | |
// Remove first array item (theme namespace) and last array item (filename). | |
// Anything in between will go in the path. | |
$class_path .= implode( DIRECTORY_SEPARATOR, array_slice( $file_parts, 1, count( $file_parts ) - 2 ) ) . '/'; | |
} | |
// Construct file path + name. | |
$file = $class_path . 'class-' . end( $file_parts ) . '.php'; | |
if ( file_exists( $file ) ) { | |
require_once $file; | |
} else { | |
echo "GTFO: `{$file}` does not exist.<br />"; | |
} | |
} | |
spl_autoload_register( 'xx_name_autoloader' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This autoloader looks for class files stored in the theme directory
inc/classes
that are properly namespaced usingTheme_Name
, and sotring classes with sub-namespaces in subdirectories.Example:
Theme_Name\Display_Classes\Render_Content
would be loaded frominc/classes/display-classes/class-render-content.php
.