Reputation: 859
Trying to make a form to upload an image to Wordpress, then set that image as a post's thumbnail. But I can't seem to get the media_handle_upload() function to work properly.
the form's input for the file
<input type="file" name="image" />
then this is the server side code
media_handle_upload( $_FILES['image'], 22 );
and this is what I get returned
object(WP_Error)#212 (2) { ["errors"]=> array(1) { ["upload_error"]=> array(1) { [0]=> string(212) "File is empty...." } } ["error_data"]=> array(0) { } }
I have played around with a couple different ways to enter the file variable,but none seems to work, am I doing that from, what exactly is the $file_id;
Upvotes: 3
Views: 12156
Reputation: 1
// Handle file upload
if (isset($_FILES['fileToUpload']) && !empty($_FILES['fileToUpload']['name'])) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_id = media_handle_upload('fileToUpload', $post_id);
if (is_wp_error($attachment_id)) {
echo 'Error uploading image: ' . $attachment_id->get_error_message();
} else {
set_post_thumbnail($post_id, $attachment_id);
}
}
return $post_id ? '<p>Post created successfully!</p>' : '<p>Error creating post!</p>';
}
Upvotes: 0
Reputation: 30001
Looking at documentation
for media_handle_upload()
, the first parameter should be the name of the index for the file in the $_FILES
array, so in your case it should look like this:
media_handle_upload('image', 22);
Upvotes: 6