require_once(ABSPATH . ‘wp-admin/includes/image.php’);
$attach_data = wp_generate_attachment_metadata($attach_id, $newupload);
This WordPress code is used to upload and insert an attachment into the media library. It creates an array of the file’s properties, including name, type, temp name, error, and size. It then creates a new upload and an attachment array with post mime type, post title, post content and post status. It then inserts the attachment into the media library and generates the attachment metadata before updating the attachment metadata.