我正在创建一个WordPress插件,允许用户将排序规则应用于特定模板(页面,存档,单个模板等(。我正在使用 PHP scandir 填充页面列表,如下所示:
$files = scandir(get_template_directory());
问题是我将单个模板.php保存在"/single"子文件夹中,因此上述函数不会调用这些模板。
如何在 scandir 函数中使用多个目录(也许是一个数组?(还是需要不同的解决方案?
所以基本上我正在尝试:
$files = scandir( get_template_directory() AND get_template_directory().'/single' );
我当前的解决方案(不是很优雅,因为每个循环需要 2 个(:
function query_caller_is_template_file_get_template_files()
{
$template_files_list = array();
$files = scandir(get_template_directory());
$singlefiles = scandir(get_template_directory().'/single');
foreach($files as $file)
{
if(strpos($file, '.php') === FALSE)
continue;
$template_files_list[] = $file;
}
foreach($singlefiles as $singlefile)
{
if(strpos($file, '.php') === FALSE)
continue;
$template_files_list[] = $singlefile;
}
return $template_files_list;
}
首先,你正在做的事情并没有错。您有两个目录,因此您执行两次相同的操作。当然,你可以让它看起来更干净一点,避免公然复制粘贴:
$files = array_merge(
scandir(get_template_directory()),
scandir(get_template_directory().'/single')
);
现在只需遍历单个数组。
在您的情况下,递归获取文件列表没有意义,因为可能存在您不想检查的子目录。如果您确实想递归到子目录中,opendir()
和readdir()
以及is_dir()
将允许您构建递归扫描函数。
您可以使用array_filter()
稍微收紧'.php'
过滤器部分。
$files = array_filter($files, function($file){
return strpos($file, '.php');
});
在这里,我假设如果一个文件以 .php
开头,你对它作为你的列表并不真正感兴趣(因为在这种情况下strpos()
会返回 0
的虚假值(。我还假设您确定不会有.php
在中间某处的文件。
比如,template.php.bak
,因为你将使用版本控制来做这样的事情。
但是,如果有可能,您可能需要稍微收紧检查以确保.php
位于文件名的末尾。