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

Hello, I am a Web Developer who loves building, editing and extending WordPress themes and plugins ;-)

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

  1. We\’re a group of volunteers and starting a new scheme in our community.
    Your site provided us with valuable info to work on. You have done an impressive job and our entire community will be grateful to you.

Leave a Reply

Your email address will not be published.