前端上传到媒体库的回调函数
wptutor
2024-08-31
13 Views
function cud_handle_file_upload_to_media() {
check_ajax_referer('file_upload_nonce', 'nonce');
if(!current_user_can('edit_posts')) {
wp_send_json_error(array('message' => 'You are not allowed to upload this file'));
}
check_file_type($_FILES['csv_data_file']);
check_file_size($_FILES['csv_data_file']);
if(!isset($_FILES['csv_data_file'])) {
wp_send_json_error(array('message' => 'No file was uploaded'));
}
$file = $_FILES['csv_data_file'];
$upload_overrides = array('test_form' => false);
//wp handle upload 返回错误 如果没成功 ,成功就返回文件数组信息,key 打印出来
$movefile = wp_handle_upload($file, $upload_overrides);
if($movefile && !isset($movefile['error'])) {
$file_url = $movefile['url'];
$file_type = $movefile['type'];
$file_name = basename($movefile['name']);
//store file information in the database
$file_data = array(
'post_title' => $file_name,
'post_content' => '',
'post_status' => 'inherit',
'post_mime_type' => $file_type
);
//这里把它传到attchment media 库里, 我们插件是要传到自己的table里
$attch_id = wp_insert_attachment($file_data, $movefile['file']);
if(!is_wp_error($attch_id)) {
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata($attch_id, $movefile['file']);
wp_update_attachment_metadata($attch_id, $attachment_data);
wp_send_json_success(array('message' => 'File Uploade succesfully!','attachment_id' => $attch_id));
} else {
wp_send_json_error(array('message' => 'Error storing file information in the database'));
}
} else {
wp_send_json_error(array('message' => $movefile['error']));
}
}