php - 从父文件夹中获取同名文件的函数

标签 php wordpress wpbakery

我已经为 WPBakery 创建了自定义元素。在 functions.php 文件中,我当前有以下内容:

add_action( 'vc_before_init', 'vc_before_init_actions' );

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

但是,当我构建更多自定义元素时,该列表将会很大。我想要做的是加载每个 vc_elements 子文件夹中名为 init.php 的所有文件。

这是我当前的文件夹结构:

vc_elements
   text-image
      init.php
   text
      init.php

最干净的方法是什么?

最佳答案

您需要使用RecursiveDirectoryIterator扫描文件夹并获取所有名为init.php的文件。以下是您可以使用的代码

add_action( 'vc_before_init', 'vc_before_init_actions' );

function vc_before_init_actions() {
    $dir = '/full_path_to_vc_elements';
    $files = getFiles($dir, 'init.php');
    foreach( $files as $file) {
        require_once( $file );
    }

}

function getFiles($dir, $match) {
    $return = array();
    $iti = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach($iti as $file){
         if ($file->isDir()) {
            continue;
         }
         if(strpos($file , $match) !== false){
            $return[] = $file->getPathname();
         }
    }
    return $return;
}

因此,将来如果您在文件夹中添加任何 init.php 文件,getFiles() 会自动选择该文件并使用 require 包含该文件。

关于php - 从父文件夹中获取同名文件的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56983573/

相关文章:

php检查gravatar是否存在header错误

python - 如何结合基于ubuntu和nginx的django和wordpress

css - WP Bakery 选项卡动画覆盖

php - 期望永远不会使用某些参数调用方法

php - 仅第三个变量中的非法字符串偏移

mysqltuner对my.cnf的建议和修改

html - 我似乎在某些页面的页脚中丢失了 CSS 代码

php-bcmath 错误 - 扩展未在 php7 中加载

php - 自动将 WooCommerce 中特定产品的订单状态更改为已完成