我想扫描插件目录中具有特定扩展名的文件,如php、css和js。
我知道有scandir()
中的函数WP_Theme
非常适合这项工作的类。问题是private
所以我不能在课外使用它。
有什么建议吗?最好的方法是什么?是否可以使用其他本机WP函数?
非常感谢,Dasha
我想扫描插件目录中具有特定扩展名的文件,如php、css和js。
我知道有scandir()
中的函数WP_Theme
非常适合这项工作的类。问题是private
所以我不能在课外使用它。
有什么建议吗?最好的方法是什么?是否可以使用其他本机WP函数?
非常感谢,Dasha
感谢大家的投入和建议。
我决定在WP_Theme::scandir()
功能本身。我了解那里发生了什么,没有其他本机WP功能来扫描目录中具有特定扩展名的文件(带有扫描子文件夹的选项)。
P、 我不知道如何链接到WP代码。这是WP_Theme::scandir()
截至2014年1月13日
/**
* Scans a directory for files of a certain extension.
*
* @since 3.4.0
* @access private
*
* @param string $path Absolute path to search.
* @param mixed Array of extensions to find, string of a single extension, or null for all extensions.
* @param int $depth How deep to search for files. Optional, defaults to a flat scan (0 depth). -1 depth is infinite.
* @param string $relative_path The basename of the absolute path. Used to control the returned path
* for the found files, particularly when this function recurses to lower depths.
*/
private static function scandir( $path, $extensions = null, $depth = 0, $relative_path = \'\' ) {
if ( ! is_dir( $path ) )
return false;
if ( $extensions ) {
$extensions = (array) $extensions;
$_extensions = implode( \'|\', $extensions );
}
$relative_path = trailingslashit( $relative_path );
if ( \'/\' == $relative_path )
$relative_path = \'\';
$results = scandir( $path );
$files = array();
foreach ( $results as $result ) {
if ( \'.\' == $result[0] )
continue;
if ( is_dir( $path . \'/\' . $result ) ) {
if ( ! $depth || \'CVS\' == $result )
continue;
$found = self::scandir( $path . \'/\' . $result, $extensions, $depth - 1 , $relative_path . $result );
$files = array_merge_recursive( $files, $found );
} elseif ( ! $extensions || preg_match( \'~\\.(\' . $_extensions . \')$~\', $result ) ) {
$files[ $relative_path . $result ] = $path . \'/\' . $result;
}
}
return $files;
}
您可以使用PHP5RecursiveDirectoryIterator 具有RecursiveIteratorIterator
$directory = \'/project_root/wp-content/plugins/your-plugin\'; //Your plugin dir
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while ($it->valid()) { //Check the file exist
if (!$it->isDot()) { //if not parent ".." or current "."
if (strpos($it->key(), \'.php\') !== false
|| strpos($it->key(), \'.css\') !== false
|| strpos($it->key(), \'.js\') !== false
) {
//Do your stuff with matched extension files
echo $it->key() . \'<br>\'; //output: main.js, index.php, style.css etc....
}
}
}
自WP 3.4起,有一个get_files()
方法您可以创建WP_Theme
插件目录设置为主题根目录的实例。
// get theme instance of WP_Theme
$current_dir = new WP_Theme(\'my-plugin-dir\',WP_PLUGIN_DIR);
// get js and css files up to 10 subfolders depth
$files = $current_dir->get_files( array(\'js\',\'css\') , 10 );
在WP-Codex Page, 那么看看source code 可能更有教育意义。在WordPress中,我一直在安装和使用各种主题,包括2013、Roots和现在的BlankSlate。我注意到现在我激活了BlankSlate,函数get_template_directory() 用于首页。php仍在返回根主题目录的路径。我当前的头版。php如下所示。<?php get_header(); ?> <section id=\"content\" role=\"main\"> <img class=\"frontpageimg\