Skip to content

Instantly share code, notes, and snippets.

@afragen
Last active December 9, 2021 05:12
Show Gist options
  • Select an option

  • Save afragen/c88f1ad9a2c3143255bf36e2582df600 to your computer and use it in GitHub Desktop.

Select an option

Save afragen/c88f1ad9a2c3143255bf36e2582df600 to your computer and use it in GitHub Desktop.
/**
* Moves a directory from one location to another via the rename() PHP function.
* If the renaming failed, falls back to copy_dir().
*
* Assumes that WP_Filesystem() has already been called and setup.
*
* @since 5.9.0
*
* @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
*
* @param string $from Source directory.
* @param string $to Destination directory.
* @param string $working_dir Optional. Remote file source directory.
* Default empty string.
* @return true|WP_Error True on success, WP_Error on failure.
*/
function move_dir( $from, $to, $working_dir = '' ) {
global $wp_filesystem;
$result = false;
if ( 'direct' === $wp_filesystem->method ) {
$wp_filesystem->rmdir( $to );
$result = @rename( $from, $to );
}
if ( ! $result && ! $wp_filesystem->is_dir( $to ) ) {
if ( ! $wp_filesystem->mkdir( $to, FS_CHMOD_DIR ) ) {
return new WP_Error( 'mkdir_failed_move_dir', __( 'Could not create directory.' ), $to );
}
$result = copy_dir( $from, $to );
}
// Clear the working directory?
if ( ! empty( $working_dir ) ) {
$wp_filesystem->delete( $working_dir, true );
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment