Using WordPress ‘move_dir()’ PHP function

The move_dir() WordPress PHP function moves a directory from one location to another. It recursively invalidates OPcache on success and falls back to copy_dir() if renaming fails.

Usage

move_dir($from, $to, $overwrite = false);

Parameters

  • $from (string) – Source directory.
  • $to (string) – Destination directory.
  • $overwrite (bool) – Optional. Whether to overwrite the destination directory if it exists. Default is false.

More information

See WordPress Developer Resources: move_dir()

Examples

Move a directory without overwriting

This example moves the “old_folder” directory to the “new_folder” directory without overwriting any existing files or folders.

$from = '/path/to/old_folder';
$to = '/path/to/new_folder';
$overwrite = false;

move_dir($from, $to, $overwrite);

Move a directory with overwriting

This example moves the “old_folder” directory to the “new_folder” directory, overwriting any existing files or folders.

$from = '/path/to/old_folder';
$to = '/path/to/new_folder';
$overwrite = true;

move_dir($from, $to, $overwrite);

Move a directory inside another directory

This example moves the “old_folder” directory inside the “parent_folder” directory.

$from = '/path/to/old_folder';
$to = '/path/to/parent_folder/old_folder';

move_dir($from, $to);

Move a directory and check for errors

This example moves the “old_folder” directory to the “new_folder” directory and checks for errors during the process.

$from = '/path/to/old_folder';
$to = '/path/to/new_folder';

$result = move_dir($from, $to);

if (is_wp_error($result)) {
    echo 'Error: ' . $result->get_error_message();
} else {
    echo 'Directory moved successfully';
}

Move a directory with a custom filter

This example moves the “old_folder” directory to the “new_folder” directory, but only if the “new_folder” directory does not exist.

$from = '/path/to/old_folder';
$to = '/path/to/new_folder';

if (!file_exists($to)) {
    move_dir($from, $to);
} else {
    echo 'The destination directory already exists';
}