要求在文件夹中找到所有块(而不是全部写出)

时间:2019-06-24 08:27:36

标签: php html wordpress

我正在为Visual Composer WP Plugin创建自定义元素。在functions.php中,我引用了每个块,以便将其加载到管理端:

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

但是,如果我有20个自定义元素,则必须单独引用它们。有没有办法只加载vc_elements文件夹中的所有块?

我知道一个潜在的绊脚石是我的每个custom elements都位于不同的文件夹中(即hero.php位于vc_elements > hero > hero.php中)。我当前的文件夹结构可以吗?

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:仅当该文件位于您提供给函数requireBlockFiles的路径的子文件夹中时,才需要该文件。 该文件为PHP文件< strong>和文件夹名称与文件名匹配(例如,子文件夹hero.php中的文件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');
}

注意:文件夹名称和文件名之间的匹配将区分大小写。