How to include all files within a folder to functions.php?

My functions.php includes other function files located within a ‘functions’ directory.

Currently they’re individually added, in the format of this example:

include('functions/login.php');

How can I modify this to include all files within the ‘functions’ directory, without listing them individually?

2 Answers
2

You can include/require all *.php files recursively using following function.

foreach(glob(get_template_directory() . "/*.php") as $file){
    require $file;
}

Alternatively You can use following function as-well.

$Directory = new RecursiveDirectoryIterator(get_template_directory().'functions/');
$Iterator = new RecursiveIteratorIterator($Directory);
$Regex = new RegexIterator($Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);

foreach($Regex as $yourfiles) {
    include $yourfiles->getPathname();
}

P.S Got the solution From Here.

Leave a Comment