Skip to content

Instantly share code, notes, and snippets.

@otakupahp
Last active August 24, 2022 10:09
Show Gist options
  • Select an option

  • Save otakupahp/e4a7337b2a1b689e73bdcfe7cdcf16d7 to your computer and use it in GitHub Desktop.

Select an option

Save otakupahp/e4a7337b2a1b689e73bdcfe7cdcf16d7 to your computer and use it in GitHub Desktop.
Simple WordPress Autoloader
<?php
spl_autoload_register(function($required_file) {
# Transform file name from class based to file based
$fixed_name = strtolower( str_ireplace( '_', '-', $required_file ) );
$file_path = explode( '\\', $fixed_name );
$last_index = count( $file_path ) - 1;
$file_name = "class-{$file_path[$last_index]}.php";
# Get fully qualified path
$fully_qualified_path = trailingslashit( dirname(__FILE__) );
for ( $key = 1; $key < $last_index; $key++ ) {
$fully_qualified_path .= trailingslashit( $file_path[ $key ] );
}
$fully_qualified_path .= $file_name;
# Include the file
if ( stream_resolve_include_path($fully_qualified_path) ) {
include_once $fully_qualified_path;
}
});
@otakupahp
Copy link
Author

otakupahp commented Sep 16, 2020

Put this code in the root file of your plugin.

To make it work, make sure that all the files that you want to load automatically have defined a namespace:

namespace UniqueName\Folder_URL\File_Name;

The UniqueName part will be omitted and the path will be loaded from the Folder_URL part. Remember that the "_" will be replaced for "-" and file names must be names "class-".

Please check the WordPress naming conventions for more information.

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