我在Bluehost上安装WordPress时遇到过一些情况,我的WordPress主题遇到了错误,因为上传文件夹wp-content/uploads不存在。
显然Bluehost cPanel WordPress安装程序不会创建这个文件夹,但HostGator可以。
因此,我需要向我的主题添加代码,以检查文件夹并创建它。
我在Bluehost上安装WordPress时遇到过一些情况,我的WordPress主题遇到了错误,因为上传文件夹wp-content/uploads不存在。
显然Bluehost cPanel WordPress安装程序不会创建这个文件夹,但HostGator可以。
因此,我需要向我的主题添加代码,以检查文件夹并创建它。
当前回答
递归创建目录路径:
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
灵感来自Python的os.makedirs()
其他回答
快速创建文件夹的方法:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
最好的方法是使用wp_mkdir_p函数。此函数将递归地创建具有正确权限的文件夹。
此外,你可以跳过文件夹存在条件,因为函数返回:
当目录已创建或以前存在时,为 如果不能创建目录,则为False。
例子:
$path = 'path/to/directory';
if ( wp_mkdir_p( $path ) ) {
// Directory exists or was created.
}
更多:https://developer.wordpress.org/reference/functions/wp_mkdir_p/
递归创建目录路径:
function makedirs($dirpath, $mode=0777) {
return is_dir($dirpath) || mkdir($dirpath, $mode, true);
}
灵感来自Python的os.makedirs()
给你。
if (!is_dir('path/to/directory')) {
if (!mkdir('path/to/directory', 0777, true) && !is_dir('path/to/directory')) {
throw new \RuntimeException(sprintf('Directory "%s" was not created', 'path/to/directory'));
}
}
你首先需要检查目录是否存在file_exists('path_to_directory')
然后使用mkdir(path_to_directory)创建一个目录
mkdir( string $pathname [, int $mode = 0777 [, bool $recursive = FALSE [, resource $context ]]] ) : bool
这里有更多关于mkdir()的信息
完整代码:
$structure = './depth1/depth2/depth3/';
if (!file_exists($structure)) {
mkdir($structure);
}