Last active
December 11, 2024 19:37
-
-
Save Arifursdev/44b6af2a28f69ff319bae1d1c8ac81dd to your computer and use it in GitHub Desktop.
Upload files to WordPress PHP
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
<?php | |
$final_submission = []; | |
if ( isset( $_FILES['files'] ) && is_array( $_FILES['files']) && !empty( $_FILES['files'] ) ) { | |
$files = $_FILES['files']; | |
$allowed_file_types = ['image/jpeg', 'image/png', 'video/mp4']; | |
$max_file_size = 5 * 1024 * 1024; // 5MB | |
$max_files = 5; | |
if ( count( $files['name'] ) > $max_files ) { | |
wp_send_json_error( 'Maximum 5 files are allowed' ); | |
} | |
foreach ( $files['name'] as $key => $file_name ) { | |
$file_type = $files['type'][$key]; | |
$file_size = $files['size'][$key]; | |
$file_error = $files['error'][$key]; | |
if ( ! in_array( $file_type, $allowed_file_types ) ) { | |
wp_send_json_error( 'Only JPG, PNG and MP4 files are allowed' ); | |
} | |
if ($file_size === 0) { | |
wp_send_json_error( 'One or more files are empty' ); | |
} | |
if ( $file_size > $max_file_size ) { | |
wp_send_json_error( 'File size exceeds the limit' ); | |
} | |
if ( $file_error !== UPLOAD_ERR_OK ) { | |
wp_send_json_error( 'File upload error' ); | |
} | |
} | |
if ( ! function_exists( 'wp_handle_upload' ) ) { | |
require_once( ABSPATH . 'wp-admin/includes/file.php' ); | |
} | |
$uploaded_files = []; | |
foreach ( $files['name'] as $key => $file_name ) { | |
$file = [ | |
'name' => $file_name, | |
'size' => $files['size'][$key], | |
'type' => $files['type'][$key], | |
'tmp_name' => $files['tmp_name'][$key], | |
'error' => $files['error'][$key], | |
'full_path' => $files['tmp_name'][$key], | |
'type' => $files['type'][$key], | |
]; | |
$allowed_mimes = [ | |
'jpg|jpeg|jpe' => 'image/jpeg', | |
'png' => 'image/png', | |
'mp4' => 'video/mp4', | |
]; | |
$upload = wp_handle_upload( $file, [ | |
'test_form' => false, | |
'mimes' => $allowed_mimes, | |
]); | |
if ( isset( $upload['error'] ) ) { | |
wp_send_json_error( $upload['error'] ); | |
} | |
$uploaded_files[] = $upload; | |
} | |
$final_submission['files'] = $uploaded_files; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment