我在Bluehost上安装WordPress时遇到过一些情况,我的WordPress主题遇到了错误,因为上传文件夹wp-content/uploads不存在。

显然Bluehost cPanel WordPress安装程序不会创建这个文件夹,但HostGator可以。

因此,我需要向我的主题添加代码,以检查文件夹并创建它。


当前回答

你首先需要检查目录是否存在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);
}

其他回答

最好的方法是使用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/

我需要一个登录网站同样的东西。我需要创建一个包含两个变量的目录。

$目录是主文件夹,我想在其中创建另一个带有用户许可证号码的子文件夹。

include_once("../include/session.php");

$lnum = $session->lnum; // Users license number from sessions
$directory = uploaded_labels; // Name of directory that folder is being created in

if (!file_exists($directory . "/" . $lnum)) {
    mkdir($directory . "/" . $lnum, 0777, true);
}
$upload = wp_upload_dir();
$upload_dir = $upload['basedir'];
$upload_dir = $upload_dir . '/newfolder';
if (! is_dir($upload_dir)) {
   mkdir( $upload_dir, 0700 );
}

如果您想避免file_exists vs. is_dir问题,我建议您看一下这里。

我尝试了这一点,它只创建目录,如果目录不存在。它不关心是否有同名的文件。

/* Creates the directory if it does not exist */
$path_to_directory = 'path/to/directory';
if (!file_exists($path_to_directory) && !is_dir($path_to_directory)) {
    mkdir($path_to_directory, 0777, true);
}

这里有一些更通用的东西,因为它出现在谷歌上。虽然细节更具体,但这个问题的标题更具有普遍性。

/**
 * recursively create a long directory path
 */
function createPath($path) {
    if (is_dir($path)) 
        return true;
    $prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
    $return = createPath($prev_path);
    return ($return && is_writable($prev_path)) ? mkdir($path) : false;
}

这将采用一条路径,可能包含一长串未创建的目录,并继续向上移动一个目录,直到到达一个现有目录。然后,它将尝试在该目录中创建下一个目录,直到创建所有目录为止。如果成功则返回true。

它可以通过提供一个停止级别来改进,这样它就会在超出用户文件夹或其他地方时失败,并包括权限。