Pages

Monday, July 8, 2013

Wordpress Upload media file from front-end


$filename = rand(1000, 10000) . str_replace(" ","-",$_FILES["video_thumbnail"]["name"]);


require_once(ABSPATH . '/wp-load.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/image.php');

$upload_overrides = array( 'test_form' => FALSE );
$uploads = wp_upload_dir();

$file_array = array(
'name' => $filename,
'type' => $_FILES['video_thumbnail']['type'],
'tmp_name' => $_FILES['video_thumbnail']['tmp_name'],
'error' => $_FILES['video_thumbnail']['error'],
'size' => $_FILES['video_thumbnail']['size'],
);

$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );

$wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );

$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$uploadfile = $uploads['path'].'/' . basename( $filename );

$attachment_id = wp_insert_attachment( $attachment, $uploadfile );

$attach_data = wp_generate_attachment_metadata( $attachment_id, $uploadfile );

$attachimage_url = $uploads['url'].'/'.basename( $filename ) ;
wp_update_attachment_metadata( $attachment_id, $attach_data );

echo json_encode(array($attachment_id, $attachimage_url));

No comments: