I would like to move attached file from one directory within WP uploads folder to another directory. The code below achieves the task. As you can see, I move the original file and also all widthxheight files automatically generated by WP (such as 150x150, 30x300). I call update_attached_file($id, $new_filepath ) and I can see the files moved, they are visible in Media library - no problem.
The issue happens when I try to rename the original file. From "name.jpg" to "username_name.jpg". Now the files are still moved to the new directory and they are renamed "username_name.jpg", "username_name-150x150.jpg", "username_name-300x300.jpg". However, WP Media library does not show the thumbnail now. It still expects "name-150x150.jpg" istead of "username_name-150x150.jpg".
The question is how can I update wordpress on the new file names for the widthxheight files? I searched and could not find any function that would give me IDs for the attachment size files. It must be possible. So many plugins do the renaming all the time...Any help?
// Get all uploaded file attachment IDs
$media_ids = $_POST['item_meta'][205]; // file upload field ID
// Loop through each attachment
foreach ( (array)$media_ids as $id ) {
if ( ! $id ) {
continue; // exit when there are no more attachments to loop through
}
// extract attachment file name without extension
$path_parts = pathinfo( get_attached_file( $id ));
$filenamenoextention = $path_parts['filename'];
// Extract username
$username = sanitize_title($_POST['item_meta'][195]);
// Set new base path
$new_filepath_base = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/';
// create user directory, if it does not exist already
$userdir = $new_filepath_base . $username;
if (!file_exists($userdir)) {
mkdir($userdir, 0775, true);
}
// Wordpress saves extra file sizes. Extract paths to all of them using wildcard *.
$original_filepaths = glob($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/form/20/' . $filenamenoextention . '*');
// Loop through WP-generated files and move them to a new location.
foreach ($original_filepaths as $original_filepath) {
// Add alt to the image. Good for SEO.
update_post_meta( $id, '_wp_attachment_image_alt', 'main profile photo - ' . $username);
// enrich filename with username and a tag
// $new_filename = $username .'_' . basename($original_filepath);
$new_filename = basename($original_filepath);
$new_filepath = $userdir . '/' . $new_filename;
$rename_result = rename($original_filepath, $new_filepath);
// If move was successful, update file path so that WP Media interface can find it.
if($rename_result)
{
update_attached_file($id, $new_filepath );
}
}
}