post_type !== 'attachment' ) { //return new WP_Error( 'invalid_attachment', 'Invalid attachment ID.' ); $error = 'Invalid attachment ID.'; } // Get the current file path $file_path = get_attached_file( $attachment_id ); $upload_dir = wp_upload_dir(); // Get the upload directory // Get the file's directory and current filename $file_dir = pathinfo( $file_path, PATHINFO_DIRNAME ); $old_filename = basename( $file_path ); $new_file_path = $file_dir . '/' . $new_filename; // Use WP_Filesystem to move (rename) the file if ( ! $wp_filesystem->move( $file_path, $new_file_path ) ) { //return new WP_Error( 'file_rename_error', 'Could not rename the file on the server using WP_Filesystem.' ); $error = 'Could not rename the file on the server using WP_Filesystem.'; } // Update the database with the new file path update_attached_file( $attachment_id, $new_file_path ); // Update the post title (optional, but usually desired) $new_title = pathinfo( $new_filename, PATHINFO_FILENAME ); // Get filename without extension wp_update_post( array( 'ID' => $attachment_id, 'post_title' => $new_title, 'post_name' => sanitize_title( $new_title ), // Update the slug ) ); // If it's an image, regenerate metadata $filetype = wp_check_filetype( $new_file_path ); if ( strpos( $filetype['type'], 'image' ) !== false ) { // Regenerate image metadata (sizes, thumbnails) $metadata = wp_generate_attachment_metadata( $attachment_id, $new_file_path ); wp_update_attachment_metadata( $attachment_id, $metadata ); } */ } catch ( Error $e ) { $error = $e->getMessage(); } return $error; } } }