从JS开始:
$(\'#logo_upload\').click(function () {
var file_data = $(\'#upload_image\').prop(\'files\')[0];
var form_data = new FormData();
form_data.append(\'upload_image\', file_data);
form_data.append(\'action\', \'uploadImages\');
form_data.append(\'security\', wp[\'security\']);
form_data.append(\'nome_associazione\', $(\'.nome-associazione\').html());
form_data.append(\'ID\', $(this).data(\'post\'));
$.ajax({
type: \'POST\',
url: wp[\'ajaxUrl\'],
processData: false,
contentType: false,
data: form_data,
success: function (response) {
console.log(response);
},
error: function (error) {
if (error.status === 403) {
location.reload();
}
},
});
});
函数调用正确。
PHP:
public static function uploadImages() {
self::checkAjaxReferer();
$params = self::parseParams($_POST[\'params\']);
$associazione = str_replace(" ", "-", $params[\'nome_associazione\']);
$postID = $params[\'ID\'];
if (isset($_FILES[\'upload_image\']))
{
$file_name = \'logo-\'.$associazione."-".$_FILES[\'upload_image\'][\'name\'];
$file_size = $_FILES[\'upload_image\'][\'size\'];
$file_tmp = $_FILES[\'upload_image\'][\'tmp_name\'];
$file_type = $_FILES[\'upload_image\'][\'type\'];
$uploadedfile = $file_name;
$upload_name = $file_name;
$uploads = wp_upload_dir();
$filepath = $uploads[\'path\'] . "/" . $upload_name;
if (!function_exists(\'wp_handle_upload\')) {
require_once(ABSPATH . \'wp-admin/includes/file.php\');
}
require_once(ABSPATH . \'wp-admin/includes/file.php\');
require_once(ABSPATH . \'wp-admin/includes/image.php\');
$upload_overrides = array(
\'test_form\' => false
);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
if ($movefile && !isset($movefile[\'error\'])) {
$file = $movefile[\'file\'];
$url = $movefile[\'url\'];
$type = $movefile[\'type\'];
// media_handle_upload( $file_handler, 0 );
$attachment = array(
\'post_mime_type\' => $type,
\'post_title\' => \'logo-\' . $associazione,
\'post_content\' => \'Image for \' . $upload_name,
\'post_status\' => \'inherit\',
\'post_parent\' => $postID
//\'post_parent\' => 0 //IF DONT WANT TO ATTACH POST ID
);
$attach_id = wp_insert_attachment($attachment, $file, $postID);
//$attach_id = wp_insert_attachment($attachment, $file, 0);//IF DONT WANT TO ATTACH POST ID
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
wp_update_attachment_metadata($attach_id, $attach_data);
echo wp_insert_post($my_post);
}
else {
die($movefile[\'error\']);
}
}
}
即使是一个小png图像,也无法通过测试。。。