Require all blocks found in folder (rather than write them all out)

Viewed 424

I'm creating custom elements for Visual Composer WP Plugin. In functions.php, I'm referencing each block so that it loads in the admin side:

function vc_before_init_actions() {
    require_once('vc_elements/hero/hero.php');  
    require_once('vc_elements/text-image/text-image.php' );  
}

However, if I have twenty custom elements, I'll have to reference them all individually. Is there a way to just load all blocks that are in the vc_elements folder?

I know a potential stumbling block would be the fact that each of my custom elements are in different folders (i.e. hero.php is in vc_elements > hero > hero.php). Is it possible with my current folder structure?

1 Answers

You can try this code: it will require the file only if that file is in a subfolder of the path you provided to the function requireBlockFiles and the file is a PHP file and the folder name matches the file name (cf file hero.php in subfolder hero)

function requireBlockFiles($dir){
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

    foreach ($rii as $file) {
        if ($file->isDir()){
            continue;
        }

        if(strtolower($file->getExtension()) === 'php' && $file->getPathInfo()->getFilename() . '.' . $file->getExtension() === $file->getFilename()){
            require_once($file->getPathname());
        }
    }
}

function vc_before_init_actions() {
    requireBlockFiles('vc_elements');
}

NOTE: this will be case sensitive for the match between folder name and file name.

Related