Last active
August 24, 2022 10:09
-
-
Save otakupahp/e4a7337b2a1b689e73bdcfe7cdcf16d7 to your computer and use it in GitHub Desktop.
Simple WordPress Autoloader
This file contains hidden or 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 | |
| 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; | |
| } | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.