You may need to auto load files in WordPress themes or plugins. But I wouldn’t recommend it if you are creating theme to sell on themeforest. They didn’t accepted themes with this auto load function few years ago when we used to sell themes on it. Here is the function to auto load or require files.

auto_load_files($path) {

    $files = glob($path);

    foreach ($files as $file) {
        require($file); 
    }

}

Now if you want to auto load .php files from includes folder in a theme you will use it as following.

auto_load_files(get_template_directory() . '/includes/*.php');

If you need to exclude a certain file like say index.php from that folder, you just need one extra line inside foreach to check if the file name is index.php then tell it to continue; to other file.

auto_load_files($path) {

    $files = glob($path);

    foreach ($files as $file) {
        if (basename($file) == 'index.php') continue; // Exclude index.php file.
        require($file); 
    }

}

Muhammad Zohaib

Web Artisan specializing in WordPress to develop custom themes, plugins, troubleshooting technical issues and ensuring websites are optimized for search engines and meet accessibility standards. Currently working as Lead Developer at XeCreators.

2 thoughts on “How to Auto Load Files in WordPress?

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.