Move a file from a directory to another

Can’t seem to track down the right filter to process this in just yet (where the edit form is being saved), especially since attachment_fields_to_edit can be used in multiple places. But maybe you already know? This will give you a good start anyway…

add_filter('??attachment_fields_save_filter??','move_attachment_directory',10,2);

function move_attachment_directory($form_fields,$post) {

$attach_id = $post->ID;
if (!isset($_POST['attachments'][$attach_id]['my_select'])) {return;}
if ($_POST['attachments'][$attach_id]['my_select'] == 'no') {return;}

// set directories
$uploaddir = wp_upload_dir();
$newdirectory = 'new-directory'; // or whatever it is

// get attachment metadata
$attachdata = wp_get_attachment_metadata($attach_id);

// move original image
$filepath = trailingslashit($uploaddir).$attachdata['file'];
$newfilepath = trailingslashit($uploaddir).trailingslashit($newdirectory).$attachdata['file'];
rename($filepath,$newfilepath);
$attachdata['file'] = trailingslashit($newdirectory).$attachdata['file'];

// move each attachment size too
foreach ($attachdata['sizes'] as $size => $data) {
    $file = $data['file'];
    $filepath = trailingslashit($uploaddir).$data['file'];
    $newfilepath = trailingslashit($uploaddir).trailingslashit($newdirectory).$data['file'];
    rename($filepath,$newfilepath);
    $data['file'] = trailingslashit($newdirectory).$data['file'];
    $attachdata['sizes'][$size] = $data;
}

// update attachment metadata
wp_update_attachment_metadata($attach_id,$attachdata);

}

Note: I don’t think this will work as is if you have media sorted by month/year on.

In any case this is untested code and may have path bugs etc., so may need some work in a test environment, but it shows it can be done and hopefully it gets you to the next step…