I am working on a simple front end image upload in WordPress. With this piece of code I can upload to the wordpress media section but I only upload the name and url of the file then, no image.
Does anyone know what I need to do to upload the image also?
My form:
<form id="dash_action" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input name="submit" type="submit" class="button" value="<?php _e( 'Save settings' ); ?>" />
</form><!--End dash_action-->
My PHP form handling:
if( isset( $_POST['submit'] ) ) {
$filename = $_FILES['file']['name'];
$wp_filetype = wp_check_filetype( basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['subdir'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, 37 );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
The WordPress codex states that “The file MUST be on the uploads directory”. I’ve added a line to move the uploaded file into the uploads directory and changed the guid path.
media_handle_sideload
is your friend!usage:
So your code is dramatically reduced in size to:
You can also pass in an array of post data with a title etc
It will move your file into the correct location automatically, create an attachment and generate the meta data, attach it to the relevant post, and give you an attachment ID in return.
Be sure to use
is_wp_error()
to check for failure.Just use
media_handle_upload()
instead. It does all this for you, including the metadata generation and everything else.If you do want to roll your own this way, then you forgot about calling
wp_handle_upload()
to actually move the file to the right place.