Javascript,Nodejs,MongodDB,WordPress,CSS,PHP

LightBlog

Sunday, December 2, 2018

How to upload file in media using form or template in wordpress

In this post we learn how to upload a file into media library of wordpress using template.
upload image is not a simple as in core php,we need some core file of wordpress which help to upload a file from template,this will also upload multiple file at a same time,
let's see the core file of wordpress which is need to included.
this file available inside wp-admin/includes folder of wordpress.

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

<?php 
/* Template Name: meta query*/
?>
<h3>File Upload in media library</h3>

<?php 

if (isset($_POST['submit'])) 
{ 
$files = $_FILES["file"];  
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 ("file" => $file); 
foreach ($_FILES as $file => $array) {              
$newupload = frontend_handle_attachment( $file, $post_id )
}


}
function frontend_handle_attachment($file_handler,$post_id) {
// 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');

$attach_id = media_handle_upload( $file_handler, $post_id );

// Set featured image 
set_post_thumbnail($post_id, $attach_id);
return $attach_id;
}
?>
<form method="post" action="" enctype="multipart/form-data">

<input type="file" name="file[]" multiple="multiple" />
<input type="submit" value="Upload" id="submit" name="submit"/>

</form>

No comments:

Post a Comment