Here is the code that works. Files are moved to ‘username’ folder and names for all files (including width x height) are updated.
// 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 username
$username = sanitize_title($_POST['item_meta'][195]);
// Set filenames and paths
$old_filename_mainmedia = basename( get_attached_file( $id ) );
$new_filename_mainmedia = $username . '_' . $old_filename_mainmedia;
$old_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/' . $old_filename_mainmedia;
$new_filepath_mainmedia = $_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/' . $username ."https://wordpress.stackexchange.com/" . $new_filename_mainmedia;
// create user directory, if it does not exist already
if (!file_exists($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username)) {
mkdir($_SERVER['DOCUMENT_ROOT'] . '/wp-content/uploads/profiles/pro/' . $username, 0775, true);
}
// Construct attachment metadata: https://codex.wordpress.org/Function_Reference/wp_get_attachment_metadata
$meta = wp_get_attachment_metadata($id);
$meta['file'] = str_replace( $old_filename_mainmedia, $new_filename_mainmedia, $meta['file'] );
// Rename the original file
rename($old_filepath_mainmedia, $new_filepath_mainmedia);
// Rename the sizes
$old_filename_sizemedia = pathinfo( basename( $old_filepath_mainmedia ), PATHINFO_FILENAME );
$new_filename_sizemedia = pathinfo( basename( $new_filepath_mainmedia ), PATHINFO_FILENAME );
foreach ( (array)$meta['sizes'] AS $size => $meta_size ) {
$old_filepath_sizemedia = dirname( $old_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];
$meta['sizes'][$size]['file'] = str_replace( $old_filename_sizemedia, $new_filename_sizemedia, $meta['sizes'][$size]['file'] );
$new_filepath_sizemedia = dirname( $new_filepath_mainmedia ).DIRECTORY_SEPARATOR.$meta['sizes'][$size]['file'];
rename( $old_filepath_sizemedia, $new_filepath_sizemedia );
}
// Add alt to the image. Good for SEO.
update_post_meta( $id, '_wp_attachment_image_alt', 'Gritmatch Pro - main profile photo - ' . $username);
// Update media library post title
$post = get_post($id);
$post->post_title = $new_filename_mainmedia;
$post->post_excerpt = "this is caption";
$post->post_content = "this is content";
$post->post_name = "this is post name";
wp_update_post( $post );
// Update WordPress
wp_update_attachment_metadata( $id, $meta );
update_attached_file($id, $new_filepath_mainmedia );
} // end looping through each media attachment