通过WordPress文件系统抽象将目录从一个位置复制到另一个位置。

原型

copy_dir( string $from, string $to, array $skip_list = array() )

描述

假设已经调用并设置了WP_Filesystem()。

参数

$from (string) (Required) 源目录

$to (string) (Required) 目的地目录

$skip_list (array) (Optional) 要跳过复制的文件/文件夹列表

返回值

(mixed)  

源文件

路径:wp-admin/includes/file.php

<?php
...
function copy_dir($from, $to, $skip_list = array() ) {
	global $wp_filesystem;
	$dirlist = $wp_filesystem->dirlist($from);
	$from = trailingslashit($from);
	$to = trailingslashit($to);
	foreach ( (array) $dirlist as $filename => $fileinfo ) {
		if ( in_array( $filename, $skip_list ) )
			continue;
		if ( 'f' == $fileinfo['type'] ) {
			if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
				// If copy failed, chmod file to 0644 and try again.
				$wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
				if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
					return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
			}
		} elseif ( 'd' == $fileinfo['type'] ) {
			if ( !$wp_filesystem->is_dir($to . $filename) ) {
				if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
					return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
			}
			// generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list
			$sub_skip_list = array();
			foreach ( $skip_list as $skip_item ) {
				if ( 0 === strpos( $skip_item, $filename . '/' ) )
					$sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
			}
			$result = copy_dir($from . $filename, $to . $filename, $sub_skip_list);
			if ( is_wp_error($result) )
				return $result;
		}
	}
	return true;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/copy_dir/