全部,我使用这个输入字段:
<input type="file" name="image_to_upload_image" accept="image/*">
然后我尝试用以下代码处理文件上传:
if ( $_FILES["image_to_upload_image"] ) {
echo "it will try and upload";
$file = $_FILES["image_to_upload_image"];
print_r($file);
$newupload = bmt_handle_attachment_new_post($file,$post_id);
echo "The newupload is: ".$newupload;
set_post_thumbnail( $post_id, $newupload );
}
它调用以下函数:
function bmt_handle_attachment_new_post($file_handler,$post_id,$set_thu=false) {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attachment_id = media_handle_upload( $file_handler, $post_id );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
} else {
// The image was uploaded successfully!
}
// If you want to set a featured image from your uploads.
return $attachment_id;
}
我正在做与此示例相同的事情:http://codex.wordpress.org/Function_Reference/media_handle_upload
为什么说偏移类型非法?
更新:我有另一个表单,除了处理多个文件上传外,它有相同的输入字段:
<input type="file" name="kv_multiple_attachments[]" multiple="multiple" >
如果我将其传递给以下表单处理程序:
if ( $_FILES ) {
$files = $_FILES["kv_multiple_attachments"];
$gallery_id = $_POST['gallery_for_upload'];
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]
);
$_FILES = array ("kv_multiple_attachments" => $file);
foreach ($_FILES as $file => $array) {
$newupload = bmt_handle_attachment($file,$pid,$gallery_id);
//$thumb_url = wp_get_attachment_thumb_url( $newupload );
//echo "<img src=".$thumb_url.">";
}
}
}
}
然后使用相同的处理功能:
function bmt_handle_attachment($file_handler,$post_id,$gallery_id,$set_thu=false) {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attachment_id = media_handle_upload( $file_handler, $post_id );
update_post_meta( $attachment_id, 'bmt_gallery_id', $gallery_id );
// If you want to set a featured image frmo your uploads.
return $attachment_id;
}
上传的文件没有任何问题。
bmt_handle_attachment
函数希望输入字段的名称作为其第一个参数。您正在传递它$_FILES["image_to_upload_image"]
,而您本应仅传递"image_to_upload_image"
。
$file = "image_to_upload_image";
$newupload = bmt_handle_attachment_new_post($file,$post_id);