Last active
September 18, 2023 19:45
-
-
Save coulterpeterson/04110024b1a0998bbe8e3622b4315bd1 to your computer and use it in GitHub Desktop.
WordPress Multi File Upload Helper Function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Takes in a PHP multi file form field (that uses the name="identifer[]" bracket notation), uploads each attachment, | |
| * provides them with attachment ids, then cleans up after itself. | |
| * Returns: array of attachment ids. | |
| * Example usage: $attachment_ids = multi_file_media_upload($_FILES['multi-upload-field']); | |
| * Example form input field: <input name="myfiles[]" type="file" multiple="true" /> | |
| */ | |
| function multi_file_media_upload($multiFile) { | |
| // TODO: Test which of these can be removed for file upload functions used | |
| require_once(ABSPATH . 'wp-admin/includes/media.php'); | |
| require_once(ABSPATH . 'wp-admin/includes/file.php'); | |
| require_once(ABSPATH . 'wp-admin/includes/image.php'); | |
| require_once(ABSPATH . 'wp-includes/pluggable.php'); | |
| $attachment_ids = array(); | |
| // for multiple file upload. | |
| $upload_overrides = array( 'test_form' => FALSE ); | |
| $files = $multiFile; | |
| foreach ( $files['name'] as $key => $value ) { | |
| if ( $files['name'][ $key ] ) { | |
| $file = array( | |
| 'name' => $files['name'][ $key ], | |
| 'type' => $files['type'][ $key ], | |
| 'tmp_name' => $files['tmp_name'][ $key ], | |
| 'error' => $files['error'][ $key ], | |
| 'size' => $files['size'][ $key ] | |
| ); | |
| // Temporary upload of the file | |
| $upload = wp_handle_upload( $file, $upload_overrides ); | |
| // Properly give the file an attachment ID | |
| $file_array = array( | |
| 'name' => $file['name'], | |
| 'tmp_name' => $upload['file'] | |
| ); | |
| array_push( $attachment_ids, media_handle_sideload($file_array) ); | |
| // Delete the temporary upload | |
| unlink( $upload['file'] ); | |
| } | |
| } | |
| return $attachment_ids; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment