I Have an issue regarding wordpress page template. I want to upload multiple zip files and extract and make those files as posts. Each zip + extracted files as a post. Every uploaded zip and extracted files in separated post.
example:
Post1 attached media: zip1 + extracted files of zip1
Post2 attached media: zip2 + extracted files of zip2
And etc..
I am able to do this except attaching zip + extracted files to post.
<?php
/*
Template Name: Help2
*/
class urm_frontend_upload {
private $wp_admin;
private $file;
private $file_split;
private $number_of_files;
static $mime_types;
static $accepted_file_types;
public $message;
/**
* Assign variables for use with the class constructor
*
* @param string $wp_admin - define path to wordpress admin file
* @param string $file - the php $_Files global data
* @param string $number_of_files - number of files in the $_FILES array
* @param string $mime_types - Uses Uploaded_Mime_Type() to set allowed file types
* @param string $accepted_file_types - gets a list of file types accepted from the $mime_types array
* @param string $message - sets comments to NULL each time class is instantiated
*
*/
function __construct($path_to_wp_admin){
//set our variables
$this->file = $_FILES['async-upload']; //$files is the $_FILES['async-upload']; array
$this->number_of_files = sizeof($this->file['name']);
$this->Uploaded_Mime_Type(); //call our accepted file type array to set the variable
$this->accepted_file_types = $this->accepted_file_types();//list of our accepted types
$this->message = '';//set our message to a NULL value
//$this->wp_admin = ABSPATH . 'wp-admin/includes/admin.php';
$this->wp_admin_path($path_to_wp_admin);
//get the wordpress admin file
require_once($this->wp_admin);
}//end class constructor
/**
* To use the wordpress upload we need access to the admin.php
* this function sets the admin path to be called in the class
* constructor
*
* @param string $path_to_wp_admin - path to wordpress admin.php
*
*/
private function wp_admin_path($path_to_wp_admin){
$this->wp_admin = $path_to_wp_admin;
}
/**
* Splits the php $_FILES array into a usable array for
* WordPress media_handle_upload(), which only allows
* for a single file upload each function call
*
* @param array $file_split - assigns the php $_FILES array to this array
*
*/
private function files_to_array(){
//split the $_FILE into an easy to iterate array
for($i=0;$i<$this->number_of_files;$i++){
$this->file_split[$i]['name'] = $this->file['name'][$i];
$this->file_split[$i]['type'] = $this->file['type'][$i];
$this->file_split[$i]['tmp_name'] = $this->file['tmp_name'][$i];
$this->file_split[$i]['error'] = $this->file['error'][$i];
$this->file_split[$i]['name'] = $this->file['name'][$i];
$this->file_split[$i]['size'] = $this->file['size'][$i];
$post_title = $_POST['post_title'] . 'post';
$new_post = array(
'post_title' => $post_title,
'post_status' => 'draft'
);
$post_id = wp_insert_post($new_post);
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
WP_Filesystem();
$to= wp_upload_dir();
$folder = $to['basedir']."/ftemp/unzipped_[$i]".basename($array['tmp_name'][$i]);
unzip_file($this->file_split[$i]['tmp_name'], $folder );
$attachment_id = media_handle_upload('async-upload', $post_id );
update_post_meta($post_id, '_thumbnail_id', $attachment_id);
}
}//end files_to_array
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param string $message - Sets the user message depending on boolean accepted mime type
* @return string $_FILES - each loop unsets the global $_FILES variable to be used again in the loop
*/
public function upload(){
//make sure multiple files are split in an array
$this->files_to_array();
//run through and upload each file
for($i=0;$i<$this->number_of_files;$i++){
$_FILES["async-upload"] = $this->file_split[$i];
if(!in_array($this->file['type'][0],$this->mime_types, true)){
$this->message(false);
//$this->message = str_replace(" ","%20",$this->message);
break;
}
else{
//it is an image, upload it
media_handle_upload('async-upload','');
$this->message(true);
unset($_FILES);
}
}
}//end upload
/**
* Defines the accepted mime types from an array. Comment out types you do not
* Wish to be accepted for upload.
*
* @param array $mime_types - Array of key->value mime type pairs
*
*/
private function Uploaded_Mime_Type() {
//edit this array to limit accepted file types
$this->mime_types = array(
/*
'txt' => 'text/plain',
'htm' => 'text/html',
'html' => 'text/html',
'php' => 'text/html',
'css' => 'text/css',
'js' => 'application/javascript',
'json' => 'application/json',
'xml' => 'application/xml',
'swf' => 'application/x-shockwave-flash',
'flv' => 'video/x-flv',
*/
// images
'png' => 'image/png',
//'jpe' => 'image/jpeg',
'zip' => 'application/zip',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
//'bmp' => 'image/bmp',
//'ico' => 'image/vnd.microsoft.icon',
//'tiff' => 'image/tiff',
//'tif' => 'image/tiff',
//'svg' => 'image/svg+xml',
//'svgz' => 'image/svg+xml',
/*
// archives
'zip' => 'application/zip',
'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload',
'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed',
// audio/video
'mp3' => 'audio/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
// adobe
'pdf' => 'application/pdf',
'psd' => 'image/vnd.adobe.photoshop',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
// ms office
'doc' => 'application/msword',
'rtf' => 'application/rtf',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
// open office
'odt' => 'application/vnd.oasis.opendocument.text',
'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
*/
);
}
/**
* Returns a list of accepted file types for easy printing/echo
*
*
* @return string $allowed . '<ul>' . $types . '</ul>';
*/
private function accepted_file_types(){
$allowed = "accepted file types are:";
foreach($this->mime_types as $key){
$types .= '<li>' . $key . '</li>';
}
return $allowed . '<ul>' . $types . '</ul>';
}
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param boolean $msg - if error $msg = false, else true
* @return string $message - returns $message
*/
public function message($msg){
//if error
if(!$msg){
$this->message = "The uploaded file is not an accepted file type please upload a valid file! " . $this->accepted_file_types;
return $this->message;
}else{
$this->message .= 'Uploaded <strong>' . $_FILES["async-upload"]['name'] . '</strong> successfuly<br>';
return $this->message;
}
}
}//
get_header();
?>
<div class="main">
<?php get_sidebar(); ?>
<div class="content-sidebar">
<?php
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
$p = ABSPATH . 'wp-admin/includes/admin.php';
$upload = new urm_frontend_upload($p);
$upload->upload();
print_r($upload->message);
}
?>
<!-- The Image Upload Form -->
<ul id="image-upload">
<form class="image-upload" id="file-form" enctype="multipart/form-data" action="<?php the_permalink(); ?>" method="POST">
<li id="async-upload-wrap">
<label for="async-upload">Upload</label>
<input type="file" id="async-upload" name="async-upload[]" multiple="true"> <input type="submit" value="Upload" name="html-upload" >
</li>
<li>
<input type="hidden" name="post_id" id="post_id" value="1199" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
</li>
</form>
</ul>
<!-- End image upload form -->
</div><!-- end content -->
</div><!-- end main -->
<?php get_footer(); ?>
Romel Apuya answers:
Hi,
Take a look at this [[LINK href="http://wordpress.stackexchange.com/questions/66651/attach-a-file-to-a-post"]]post[[/LINK]].
socialh comments:
I need a solution for my page template, this post not help me solve it.
Romel Apuya comments:
<?php
/* Template Name: Help2
*/
class urm_frontend_upload {
private $wp_admin;
private $file;
private $file_split;
private $number_of_files;
static $mime_types;
static $accepted_file_types;
public $message;
/**
* Assign variables for use with the class constructor
*
* @param string $wp_admin - define path to wordpress admin file
* @param string $file - the php $_Files global data
* @param string $number_of_files - number of files in the $_FILES array
* @param string $mime_types - Uses Uploaded_Mime_Type() to set allowed file types
* @param string $accepted_file_types - gets a list of file types accepted from the $mime_types array
* @param string $message - sets comments to NULL each time class is instantiated
*
*/
function __construct($path_to_wp_admin){
//set our variables
$this->file = $_FILES['async-upload']; //$files is the $_FILES['async-upload']; array
$this->number_of_files = sizeof($this->file['name']);
$this->Uploaded_Mime_Type(); //call our accepted file type array to set the variable
$this->accepted_file_types = $this->accepted_file_types();//list of our accepted types
$this->message = '';//set our message to a NULL value
//$this->wp_admin = ABSPATH . 'wp-admin/includes/admin.php';
$this->wp_admin_path($path_to_wp_admin);
require_once($this->wp_admin);
}//end class constructor
/**
* To use the wordpress upload we need access to the admin.php
* this function sets the admin path to be called in the class
* constructor
*
* @param string $path_to_wp_admin - path to wordpress admin.php
*
*/
private function wp_admin_path($path_to_wp_admin){
$this->wp_admin = $path_to_wp_admin;
}
/**
* Splits the php $_FILES array into a usable array for
* WordPress media_handle_upload(), which only allows
* for a single file upload each function call
*
* @param array $file_split - assigns the php $_FILES array to this array
*
*/
private function files_to_array(){
//split the $_FILE into an easy to iterate array
for($i=0;$i<$this->number_of_files;$i++){
$this->file_split[$i]['name'] = $this->file['name'][$i];
$dd = trim($this->file_split[$i]['name'],".zip");
$this->file_split[$i]['type'] = $this->file['type'][$i];
$this->file_split[$i]['tmp_name'] = $this->file['tmp_name'][$i];
$this->file_split[$i]['error'] = $this->file['error'][$i];
$this->file_split[$i]['name'] = $this->file['name'][$i];
$this->file_split[$i]['size'] = $this->file['size'][$i];
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
WP_Filesystem();
$to= wp_upload_dir();
mkdir($to['url']."/".$dd."/");
$folder = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd."/".basename($array['tmp_name'][$i]);
unzip_file($this->file_split[$i]['tmp_name'], $folder );
$ig = 0;
$jg = 0;
$files_att = array();
$files_att2 = array();
$dir = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd."/".basename($array['tmp_name'][$i]);
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$files_att[$ig]= $dir.'/'.$file;
$files_att2[$jg]= $file;
$ig++;
$jg++;
}
}
$max = $ig;
for($ii=2;$ii<$max;$ii++){
$post_title = $files_att2[$ii] . 'post';
$new_post = array(
'post_title' => $post_title,
'post_status' => 'draft'
);
$post_idw = wp_insert_post($new_post);
$image_url = $files_att[$ii];
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($to['path']))
$filess = $to['path'] . '/' . $filename;
else
$filess = $to['basedir'] . '/' . $filename;
file_put_contents($filess, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filess, $post_idw );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filess );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_idw, $attach_id );
}
}
}//end files_to_array
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param string $message - Sets the user message depending on boolean accepted mime type
* @return string $_FILES - each loop unsets the global $_FILES variable to be used again in the loop
*/
public function upload(){
//make sure multiple files are split in an array
$this->files_to_array();
//run through and upload each file
for($i=0;$i<$this->number_of_files;$i++){
$_FILES["async-upload"] = $this->file_split[$i];
if(!in_array($this->file['type'][0],$this->mime_types, true)){
$this->message(false);
//$this->message = str_replace(" ","%20",$this->message);
break;
}
else{
//it is an image, upload it
media_handle_upload('async-upload','');
$this->message(true);
unset($_FILES);
}
}
}//end upload
/**
* Defines the accepted mime types from an array. Comment out types you do not
* Wish to be accepted for upload.
*
* @param array $mime_types - Array of key->value mime type pairs
*
*/
private function Uploaded_Mime_Type() {
//edit this array to limit accepted file types
$this->mime_types = array(
// images
'png' => 'image/png',
'zip' => 'application/zip',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
);
}
/**
* Returns a list of accepted file types for easy printing/echo
*
*
* @return string $allowed . '<ul>' . $types . '</ul>';
*/
private function accepted_file_types(){
$allowed = "accepted file types are:";
foreach($this->mime_types as $key){
$types .= '<li>' . $key . '</li>';
}
return $allowed . '<ul>' . $types . '</ul>';
}
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param boolean $msg - if error $msg = false, else true
* @return string $message - returns $message
*/
public function message($msg){
//if error
if(!$msg){
$this->message = "The uploaded file is not an accepted file type please upload a valid file! " . $this->accepted_file_types;
return $this->message;
}else{
$this->message .= 'Uploaded ' . $_FILES["async-upload"]['name'] . ' successfuly<br>';
return $this->message;
}
}
}
get_header();
?>
<div class="main">
<?php get_sidebar(); ?>
<div class="content-sidebar">
<?php
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
$p = ABSPATH . 'wp-admin/includes/admin.php';
$upload = new urm_frontend_upload($p);
$upload->upload();
print_r($upload->message);
}
?>
<!-- The Image Upload Form -->
<ul id="image-upload">
<form class="image-upload" id="file-form" enctype="multipart/form-data" action="<?php the_permalink(); ?>" method="POST">
<li id="async-upload-wrap">
<label for="async-upload">Upload</label>
<input type="file" id="async-upload" name="async-upload[]" multiple="true"> <input type="submit" value="Upload" name="html-upload" >
</li>
<li>
<input type="hidden" name="post_id" id="post_id" value="1199" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
</li>
</form>
</ul>
<!-- End image upload form -->
</div><!-- end content -->
</div><!-- end main -->
<?php get_footer(); ?>
Romel Apuya comments:
<?php
/* Template Name: Help2
*/
class urm_frontend_upload {
private $wp_admin;
private $file;
private $file_split;
private $number_of_files;
static $mime_types;
static $accepted_file_types;
public $message;
/**
* Assign variables for use with the class constructor
*
* @param string $wp_admin - define path to wordpress admin file
* @param string $file - the php $_Files global data
* @param string $number_of_files - number of files in the $_FILES array
* @param string $mime_types - Uses Uploaded_Mime_Type() to set allowed file types
* @param string $accepted_file_types - gets a list of file types accepted from the $mime_types array
* @param string $message - sets comments to NULL each time class is instantiated
*
*/
function __construct($path_to_wp_admin){
//set our variables
$this->file = $_FILES['async-upload']; //$files is the $_FILES['async-upload']; array
$this->number_of_files = sizeof($this->file['name']);
$this->Uploaded_Mime_Type(); //call our accepted file type array to set the variable
$this->accepted_file_types = $this->accepted_file_types();//list of our accepted types
$this->message = '';//set our message to a NULL value
//$this->wp_admin = ABSPATH . 'wp-admin/includes/admin.php';
$this->wp_admin_path($path_to_wp_admin);
require_once($this->wp_admin);
}//end class constructor
/**
* To use the wordpress upload we need access to the admin.php
* this function sets the admin path to be called in the class
* constructor
*
* @param string $path_to_wp_admin - path to wordpress admin.php
*
*/
private function wp_admin_path($path_to_wp_admin){
$this->wp_admin = $path_to_wp_admin;
}
/**
* Splits the php $_FILES array into a usable array for
* WordPress media_handle_upload(), which only allows
* for a single file upload each function call
*
* @param array $file_split - assigns the php $_FILES array to this array
*
*/
private function files_to_array(){
//split the $_FILE into an easy to iterate array
for($i=0;$i<$this->number_of_files;$i++){
$this->file_split[$i]['name'] = $this->file['name'][$i];
$dd = trim($this->file_split[$i]['name'],".zip");
$this->file_split[$i]['type'] = $this->file['type'][$i];
$this->file_split[$i]['tmp_name'] = $this->file['tmp_name'][$i];
$this->file_split[$i]['error'] = $this->file['error'][$i];
$this->file_split[$i]['name'] = $this->file['name'][$i];
$this->file_split[$i]['size'] = $this->file['size'][$i];
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
WP_Filesystem();
$to= wp_upload_dir();
$folder = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd."/".basename($array['tmp_name'][$i]);
unzip_file($this->file_split[$i]['tmp_name'], $folder );
$ig = 0;
$jg = 0;
$files_att = array();
$files_att2 = array();
$dir = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd."/".basename($array['tmp_name'][$i]);
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$files_att[$ig]= $dir.'/'.$file;
$files_att2[$jg]= $file;
$ig++;
$jg++;
}
}
$max = $ig;
for($ii=2;$ii<$max;$ii++){
$post_title = $files_att2[$ii] . 'post';
$new_post = array(
'post_title' => $post_title,
'post_status' => 'draft'
);
$post_idw = wp_insert_post($new_post);
$image_url = $files_att[$ii];
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($to['path']))
$filess = $to['path'] . '/' . $filename;
else
$filess = $to['basedir'] . '/' . $filename;
file_put_contents($filess, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filess, $post_idw );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filess );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_idw, $attach_id );
}
}
}//end files_to_array
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param string $message - Sets the user message depending on boolean accepted mime type
* @return string $_FILES - each loop unsets the global $_FILES variable to be used again in the loop
*/
public function upload(){
//make sure multiple files are split in an array
$this->files_to_array();
//run through and upload each file
for($i=0;$i<$this->number_of_files;$i++){
$_FILES["async-upload"] = $this->file_split[$i];
if(!in_array($this->file['type'][0],$this->mime_types, true)){
$this->message(false);
//$this->message = str_replace(" ","%20",$this->message);
break;
}
else{
//it is an image, upload it
media_handle_upload('async-upload','');
$this->message(true);
unset($_FILES);
}
}
}//end upload
/**
* Defines the accepted mime types from an array. Comment out types you do not
* Wish to be accepted for upload.
*
* @param array $mime_types - Array of key->value mime type pairs
*
*/
private function Uploaded_Mime_Type() {
//edit this array to limit accepted file types
$this->mime_types = array(
// images
'png' => 'image/png',
'zip' => 'application/zip',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
);
}
/**
* Returns a list of accepted file types for easy printing/echo
*
*
* @return string $allowed . '<ul>' . $types . '</ul>';
*/
private function accepted_file_types(){
$allowed = "accepted file types are:";
foreach($this->mime_types as $key){
$types .= '<li>' . $key . '</li>';
}
return $allowed . '<ul>' . $types . '</ul>';
}
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param boolean $msg - if error $msg = false, else true
* @return string $message - returns $message
*/
public function message($msg){
//if error
if(!$msg){
$this->message = "The uploaded file is not an accepted file type please upload a valid file! " . $this->accepted_file_types;
return $this->message;
}else{
$this->message .= 'Uploaded ' . $_FILES["async-upload"]['name'] . ' successfuly<br>';
return $this->message;
}
}
}
get_header();
?>
<div class="main">
<?php get_sidebar(); ?>
<div class="content-sidebar">
<?php
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
$p = ABSPATH . 'wp-admin/includes/admin.php';
$upload = new urm_frontend_upload($p);
$upload->upload();
print_r($upload->message);
}
?>
<!-- The Image Upload Form -->
<ul id="image-upload">
<form class="image-upload" id="file-form" enctype="multipart/form-data" action="<?php the_permalink(); ?>" method="POST">
<li id="async-upload-wrap">
<label for="async-upload">Upload</label>
<input type="file" id="async-upload" name="async-upload[]" multiple="true"> <input type="submit" value="Upload" name="html-upload" >
</li>
<li>
<input type="hidden" name="post_id" id="post_id" value="1199" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
</li>
</form>
</ul>
<!-- End image upload form -->
</div><!-- end content -->
</div><!-- end main -->
<?php get_footer(); ?>
Romel Apuya comments:
Just copy that and use as page template.
Ive tested it on my side and it works.
socialh comments:
Nice work, but i tried to upload 2 zip files, and i found that it makes 5 posts, i need it only the same number of zip.
If i uploaded 3 zip files, i should get only 3 posts, and every post should contain zip file+ extracted files of that file.
Post1 attached media: zip1 + extracted files of zip1
Post2 attached media: zip2 + extracted files of zip2
Post3 attached media: zip3 + extracted files of zip3
Romel Apuya comments:
<?php
/* Template Name: Help2
*/
class urm_frontend_upload {
private $wp_admin;
private $file;
private $file_split;
private $number_of_files;
static $mime_types;
static $accepted_file_types;
public $message;
/**
* Assign variables for use with the class constructor
*
* @param string $wp_admin - define path to wordpress admin file
* @param string $file - the php $_Files global data
* @param string $number_of_files - number of files in the $_FILES array
* @param string $mime_types - Uses Uploaded_Mime_Type() to set allowed file types
* @param string $accepted_file_types - gets a list of file types accepted from the $mime_types array
* @param string $message - sets comments to NULL each time class is instantiated
*
*/
function __construct($path_to_wp_admin){
//set our variables
$this->file = $_FILES['async-upload']; //$files is the $_FILES['async-upload']; array
$this->number_of_files = sizeof($this->file['name']);
$this->Uploaded_Mime_Type(); //call our accepted file type array to set the variable
$this->accepted_file_types = $this->accepted_file_types();//list of our accepted types
$this->message = '';//set our message to a NULL value
//$this->wp_admin = ABSPATH . 'wp-admin/includes/admin.php';
$this->wp_admin_path($path_to_wp_admin);
require_once($this->wp_admin);
}//end class constructor
/**
* To use the wordpress upload we need access to the admin.php
* this function sets the admin path to be called in the class
* constructor
*
* @param string $path_to_wp_admin - path to wordpress admin.php
*
*/
private function wp_admin_path($path_to_wp_admin){
$this->wp_admin = $path_to_wp_admin;
}
/**
* Splits the php $_FILES array into a usable array for
* WordPress media_handle_upload(), which only allows
* for a single file upload each function call
* @param array $file_split - assigns the php $_FILES array to this array
*
*/
private function files_to_array(){
//split the $_FILE into an easy to iterate array
for($i=0;$i<$this->number_of_files;$i++){
$this->file_split[$i]['name'] = $this->file['name'][$i];
$dd = trim($this->file_split[$i]['name'],".zip");
$this->file_split[$i]['type'] = $this->file['type'][$i];
$this->file_split[$i]['tmp_name'] = $this->file['tmp_name'][$i];
$this->file_split[$i]['error'] = $this->file['error'][$i];
$this->file_split[$i]['name'] = $this->file['name'][$i];
$this->file_split[$i]['size'] = $this->file['size'][$i];
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
WP_Filesystem();
$to= wp_upload_dir();
mkdir($to['url']."/".$dd."/");
$folder = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd."/".basename($array['tmp_name'][$i]);
unzip_file($this->file_split[$i]['tmp_name'], $folder );
$ig = 0;
$jg = 0;
$files_att = array();
$files_att2 = array();
$dir = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd."/".basename($array['tmp_name'][$i]);
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
$files_att[$ig]= $dir.'/'.$file;
$files_att2[$jg]= $file;
$ig++;
$jg++;
}
}
}
$max = $ig;
for($ii=2;$ii<$max;$ii++){
$post_title = $files_att2[$ii] . 'post';
$new_post = array(
'post_title' => $post_title,
'post_status' => 'draft'
);
$post_idw = wp_insert_post($new_post);
$image_url = $files_att[$ii];
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($to['path']))
$filess = $to['path'] . '/' . $filename;
else
$filess = $to['basedir'] . '/' . $filename;
file_put_contents($filess, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filess, $post_idw );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filess );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_idw, $attach_id );
}
}
}//end files_to_array
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param string $message - Sets the user message depending on boolean accepted mime type
* @return string $_FILES - each loop unsets the global $_FILES variable to be used again in the loop
*/
public function upload(){
//make sure multiple files are split in an array
$this->files_to_array();
//run through and upload each file
for($i=0;$i<$this->number_of_files;$i++){
$_FILES["async-upload"] = $this->file_split[$i];
if(!in_array($this->file['type'][0],$this->mime_types, true)){
$this->message(false);
//$this->message = str_replace(" ","%20",$this->message);
break;
}
else{
//it is an image, upload it
media_handle_upload('async-upload','');
$this->message(true);
unset($_FILES);
}
}
}//end upload
/**
* Defines the accepted mime types from an array. Comment out types you do not
* Wish to be accepted for upload.
*
* @param array $mime_types - Array of key->value mime type pairs
*
*/
private function Uploaded_Mime_Type() {
//edit this array to limit accepted file types
$this->mime_types = array(
// images
'png' => 'image/png',
'zip' => 'application/zip',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'gif' => 'image/gif',
);
}
/**
* Returns a list of accepted file types for easy printing/echo
*
*
* @return string $allowed . '<ul>' . $types . '</ul>';
*/
private function accepted_file_types(){
$allowed = "accepted file types are:";
foreach($this->mime_types as $key){
$types .= '<li>' . $key . '</li>';
}
return $allowed . '<ul>' . $types . '</ul>';
}
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param boolean $msg - if error $msg = false, else true
* @return string $message - returns $message
*/
public function message($msg){
//if error
if(!$msg){
$this->message = "The uploaded file is not an accepted file type please upload a valid file! " . $this->accepted_file_types;
return $this->message;
}else{
$this->message .= 'Uploaded ' . $_FILES["async-upload"]['name'] . ' successfuly<br>';
return $this->message;
}
}
}
get_header();
?>
<div class="main">
<?php get_sidebar(); ?>
<div class="content-sidebar">
<?php
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
$p = ABSPATH . 'wp-admin/includes/admin.php';
$upload = new urm_frontend_upload($p);
$upload->upload();
print_r($upload->message);
}
?>
<!-- The Image Upload Form -->
<ul id="image-upload">
<form class="image-upload" id="file-form" enctype="multipart/form-data" action="<?php the_permalink(); ?>" method="POST">
<li id="async-upload-wrap">
<label for="async-upload">Upload</label>
<input type="file" id="async-upload" name="async-upload[]" multiple="true"> <input type="submit" value="Upload" name="html-upload" >
</li>
<li>
<input type="hidden" name="post_id" id="post_id" value="1199" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
</li>
</form>
</ul>
<!-- End image upload form -->
</div><!-- end content -->
</div><!-- end main -->
<?php get_footer(); ?>
Romel Apuya comments:
sorry forgot the {} on the if of
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
$files_att[$ig]= $dir.'/'.$file;
$files_att2[$jg]= $file;
$ig++;
$jg++;
}
socialh comments:
I tried to upload 2 zip files, it makes 3 posts, it should be 2. Extracted files is attached, but zip files is not attached to posts.
X number of zip = x number of posts
each post media files should be zip+ extracted files of this zip.
Romel Apuya comments:
How many files are there in the zip file???
socialh comments:
each zip contain 3 files like .txt, .png
I need posts the same number as zip file i upload.
If i uploaded 3 zip files = 3 posts
If i uploaded 4 zip files = 4 posts
and etc...
And each post should contain zip file+ extracted files of the same zip
Romel Apuya comments:
if you have 3 zip files which has like 3 files in each zip so you wont be getting 3 posts???
since you also want a post for each file which has the zip file + the file..??
socialh comments:
Yes if i have 3 zip files i should get only 3 posts, each zip contain images or text or pdf not other file. Extracting this file in the same post.
If i uploaded a zip file which contain 5 images, i need it to be in one post, not 5 posts.
Romel Apuya comments:
right. got that
Romel Apuya comments:
<?php
/* Template Name: Help2
*/
class urm_frontend_upload {
private $wp_admin;
private $file;
private $file_split;
private $number_of_files;
static $mime_types;
static $accepted_file_types;
public $message;
/**
* Assign variables for use with the class constructor
*
* @param string $wp_admin - define path to wordpress admin file
* @param string $file - the php $_Files global data
* @param string $number_of_files - number of files in the $_FILES array
* @param string $mime_types - Uses Uploaded_Mime_Type() to set allowed file types
* @param string $accepted_file_types - gets a list of file types accepted from the $mime_types array
* @param string $message - sets comments to NULL each time class is instantiated
*
*/
function __construct($path_to_wp_admin){
//set our variables
$this->file = $_FILES['async-upload']; //$files is the $_FILES['async-upload']; array
$this->number_of_files = sizeof($this->file['name']);
$this->Uploaded_Mime_Type(); //call our accepted file type array to set the variable
$this->accepted_file_types = $this->accepted_file_types();//list of our accepted types
$this->message = '';//set our message to a NULL value
//$this->wp_admin = ABSPATH . 'wp-admin/includes/admin.php';
$this->wp_admin_path($path_to_wp_admin);
require_once($this->wp_admin);
}//end class constructor
/**
* To use the wordpress upload we need access to the admin.php
* this function sets the admin path to be called in the class
* constructor
*
* @param string $path_to_wp_admin - path to wordpress admin.php
*
*/
private function wp_admin_path($path_to_wp_admin){
$this->wp_admin = $path_to_wp_admin;
}
/**
* Splits the php $_FILES array into a usable array for
* WordPress media_handle_upload(), which only allows
* for a single file upload each function call
*
* @param array $file_split - assigns the php $_FILES array to this array
*
*/
private function files_to_array(){
//split the $_FILE into an easy to iterate array
for($i=0;$i<$this->number_of_files;$i++){
$this->file_split[$i]['name'] = $this->file['name'][$i];
$dd = trim($this->file_split[$i]['name'],".zip");
$this->file_split[$i]['type'] = $this->file['type'][$i];
$this->file_split[$i]['tmp_name'] = $this->file['tmp_name'][$i];
$this->file_split[$i]['error'] = $this->file['error'][$i];
$this->file_split[$i]['name'] = $this->file['name'][$i];
$this->file_split[$i]['size'] = $this->file['size'][$i];
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
WP_Filesystem();
$to= wp_upload_dir();
$folder = $to['basedir']."/ftemp/unzipped_[".$i."]";
$unzipfile = unzip_file($this->file_split[$i]['tmp_name'], $folder );
//var_dump($unzipfile );
$ig = 0;
$jg = 0;
$files_att = array();
$files_att2 = array();
$dir = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd;
//var_dump($dir);
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
$files_att[$ig]= $dir.'/'.$file;
$files_att2[$jg]= $file;
$ig++;
$jg++;
//var_dump($ig);
//var_dump($jg);
}
}
}
$post_title = $dd . ' post';
$new_post = array(
'post_title' => $post_title,
'post_status' => 'draft'
);
$post_idw = wp_insert_post($new_post);
$max = $ig + 1;
$files_att[$max]= $to['url']."/".$this->file_split[$i]['name'];
//var_dump($files_att[$max]);
for($ii=0;$ii<=$max;$ii++){
$image_url = $files_att[$ii];
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($to['path']))
$filess = $to['path'] . '/' . $filename;
else
$filess = $to['basedir'] . '/' . $filename;
file_put_contents($filess, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filess, $post_idw );
$existing_download = (int) get_post_meta($post_idw, $filess, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
update_post_meta($post_idw, $filess, $attach_id);
}
}
}//end files_to_array
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param string $message - Sets the user message depending on boolean accepted mime type
* @return string $_FILES - each loop unsets the global $_FILES variable to be used again in the loop
*/
public function upload(){
//make sure multiple files are split in an array
$this->files_to_array();
//run through and upload each file
//var_dump($this->file['type']);
for($i=0;$i<$this->number_of_files;$i++){
$_FILES["async-upload"] = $this->file_split[$i];
if(!in_array($this->file['type'][0],$this->mime_types, true)){
$this->message(false);
//$this->message = str_replace(" ","%20",$this->message);
break;
}
else{
//it is an image, upload it
media_handle_upload('async-upload','');
$this->message(true);
unset($_FILES);
}
}
}//end upload
/**
* Defines the accepted mime types from an array. Comment out types you do not
* Wish to be accepted for upload.
*
* @param array $mime_types - Array of key->value mime type pairs
*
*/
private function Uploaded_Mime_Type() {
//edit this array to limit accepted file types
$this->mime_types = array(
// images
'zip' => 'application/zip',
'gz|gzip' => 'application/x-gzip',
'rar' => 'application/rar',
'7z' => 'application/x-7z-compressed',
'zip' => 'application/x-zip-compressed',
);
}
/**
* Returns a list of accepted file types for easy printing/echo
*
*
* @return string $allowed . '<ul>' . $types . '</ul>';
*/
private function accepted_file_types(){
$allowed = "accepted file types are:";
foreach($this->mime_types as $key){
$types .= '<li>' . $key . '</li>';
}
return $allowed . '<ul>' . $types . '</ul>';
}
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param boolean $msg - if error $msg = false, else true
* @return string $message - returns $message
*/
public function message($msg){
//if error
if(!$msg){
$this->message = "The uploaded file is not an accepted file type please upload a valid file! " . $this->accepted_file_types;
return $this->message;
}else{
$this->message .= 'Uploaded ' . $_FILES["async-upload"]['name'] . ' successfuly<br>';
return $this->message;
}
}
}
get_header();
?>
<div class="main">
<?php get_sidebar(); ?>
<div class="content-sidebar">
<?php
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
$p = ABSPATH . 'wp-admin/includes/admin.php';
$upload = new urm_frontend_upload($p);
$upload->upload();
print_r($upload->message);
}
?>
<!-- The Image Upload Form -->
<ul id="image-upload">
<form class="image-upload" id="file-form" enctype="multipart/form-data" action="<?php the_permalink(); ?>" method="POST">
<li id="async-upload-wrap">
<label for="async-upload">Upload</label>
<input type="file" id="async-upload" name="async-upload[]" multiple="true"> <input type="submit" value="Upload" name="html-upload" >
</li>
<li>
<input type="hidden" name="post_id" id="post_id" value="1199" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
</li>
</form>
</ul>
<!-- End image upload form -->
</div><!-- end content -->
</div><!-- end main -->
<?php get_footer(); ?>
socialh comments:
There is a great progress here in your last code. Number of zip= number of posts and attaching zip file to it. There is only one thing attaching extracted zip files content to a post, such as .png, .jpg, pdf and etc.
Your code is only attaching zip to post, not extracted files also.
Romel Apuya comments:
Actually the Uploaded_Mime_Type is just for the upload.
there is a restriction to this code. Zip file must be same name as the folder name
ex.
Test Zip - folder
Test Zip.zip - name of the zip.
Ive tested the code and the files are attached in custom fields.
socialh comments:
Hi,
I want to upload only zip, but if this zip contain 2 or 3 images or pdf files or etc after extract, i want to attach all those files to this post. Your Code is only attaching zip, and an empty folder, please check again. I need zip file content to be attached also after unzip.
Romel Apuya comments:
ok Updated now.
attached is how it loooks on my test.
<?php
/* Template Name: Help2
*/
class urm_frontend_upload {
private $wp_admin;
private $file;
private $file_split;
private $number_of_files;
static $mime_types;
static $accepted_file_types;
public $message;
/**
* Assign variables for use with the class constructor
*
* @param string $wp_admin - define path to wordpress admin file
* @param string $file - the php $_Files global data
* @param string $number_of_files - number of files in the $_FILES array
* @param string $mime_types - Uses Uploaded_Mime_Type() to set allowed file types
* @param string $accepted_file_types - gets a list of file types accepted from the $mime_types array
* @param string $message - sets comments to NULL each time class is instantiated
*
*/
function __construct($path_to_wp_admin){
//set our variables
$this->file = $_FILES['async-upload']; //$files is the $_FILES['async-upload']; array
$this->number_of_files = sizeof($this->file['name']);
$this->Uploaded_Mime_Type(); //call our accepted file type array to set the variable
$this->accepted_file_types = $this->accepted_file_types();//list of our accepted types
$this->message = '';//set our message to a NULL value
//$this->wp_admin = ABSPATH . 'wp-admin/includes/admin.php';
$this->wp_admin_path($path_to_wp_admin);
require_once($this->wp_admin);
}//end class constructor
/**
* To use the wordpress upload we need access to the admin.php
* this function sets the admin path to be called in the class
* constructor
*
* @param string $path_to_wp_admin - path to wordpress admin.php
*
*/
private function wp_admin_path($path_to_wp_admin){
$this->wp_admin = $path_to_wp_admin;
}
/**
* Splits the php $_FILES array into a usable array for
* WordPress media_handle_upload(), which only allows
* for a single file upload each function call
*
* @param array $file_split - assigns the php $_FILES array to this array
*
*/
private function files_to_array(){
//split the $_FILE into an easy to iterate array
for($i=0;$i<$this->number_of_files;$i++){
$this->file_split[$i]['name'] = $this->file['name'][$i];
$dd = trim($this->file_split[$i]['name'],".zip");
$this->file_split[$i]['type'] = $this->file['type'][$i];
$this->file_split[$i]['tmp_name'] = $this->file['tmp_name'][$i];
$this->file_split[$i]['error'] = $this->file['error'][$i];
$this->file_split[$i]['name'] = $this->file['name'][$i];
$this->file_split[$i]['size'] = $this->file['size'][$i];
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
WP_Filesystem();
$to= wp_upload_dir();
$folder = $to['basedir']."/ftemp/unzipped_[".$i."]";
$unzipfile = unzip_file($this->file_split[$i]['tmp_name'], $folder );
//var_dump($unzipfile );
$ig = 0;
$jg = 0;
$files_att = array();
$files_att2 = array();
$dir = $to['basedir']."/ftemp/unzipped_[".$i."]"."/".$dd;
//var_dump($dir);
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) {
$files_att[$ig]= $dir.'/'.$file;
$files_att2[$jg]= $file;
$ig++;
$jg++;
//var_dump($ig);
//var_dump($jg);
}
}
}
$post_title = $dd . ' post';
$new_post = array(
'post_title' => $post_title,
'post_status' => 'draft'
);
$post_idw = wp_insert_post($new_post);
$max = $ig;
$files_att[$max]= $to['url']."/".$this->file_split[$i]['name'];
//var_dump($files_att);
//var_dump($files_att[$max]);
for($ii=0;$ii<=$max;$ii++){
$image_url = $files_att[$ii];
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($to['path']))
$filess = $to['path'] . '/' . $filename;
else
$filess = $to['basedir'] . '/' . $filename;
file_put_contents($filess, $image_data);
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filess, $post_idw );
$existing_download = (int) get_post_meta($post_idw, $filess, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
$flocation_meta = 'file_location_'.$ii;
update_post_meta($post_idw, $flocation_meta, $filess, '');
}
}
}//end files_to_array
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param string $message - Sets the user message depending on boolean accepted mime type
* @return string $_FILES - each loop unsets the global $_FILES variable to be used again in the loo
*/
public function upload(){
//make sure multiple files are split in an array
$this->files_to_array();
//run through and upload each file
//var_dump($this->file['type']);
for($i=0;$i<$this->number_of_files;$i++){
$_FILES["async-upload"] = $this->file_split[$i];
if(!in_array($this->file['type'][0],$this->mime_types, true)){
$this->message(false);
//$this->message = str_replace(" ","%20",$this->message);
break;
}
else{
//it is an image, upload it
media_handle_upload('async-upload','');
$this->message(true);
unset($_FILES);
}
}
}//end upload
/**
* Defines the accepted mime types from an array. Comment out types you do not
* Wish to be accepted for upload.
*
* @param array $mime_types - Array of key->value mime type pairs
*
*/
private function Uploaded_Mime_Type() {
//edit this array to limit accepted file types
$this->mime_types = array(
// images
'zips' => 'application/zip',
'gz|gzip' => 'application/x-gzip',
'rar' => 'application/rar',
'7z' => 'application/x-7z-compressed',
'zip' => 'application/x-zip-compressed',
);
}
/**
* Returns a list of accepted file types for easy printing/echo
*
*
* @return string $allowed . '<ul>' . $types . '</ul>';
*/
private function accepted_file_types(){
$allowed = "accepted file types are:";
foreach($this->mime_types as $key){
$types .= '<li>' . $key . '</li>';
}
return $allowed . '<ul>' . $types . '</ul>';
}
/**
* Uploads the file(s) to WordPress if the file is of the accepted mime type
*
* @param boolean $msg - if error $msg = false, else true
* @return string $message - returns $message
*/
public function message($msg){
//if error
if(!$msg){
$this->message = "The uploaded file is not an accepted file type please upload a valid file! " . $this->accepted_file_types;
return $this->message;
}else{
$this->message .= 'Uploaded ' . $_FILES["async-upload"]['name'] . ' successfuly<br>';
return $this->message;
}
}
}
get_header();
?>
<div class="main">
<?php get_sidebar(); ?>
<div class="content-sidebar">
<?php
if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) {
$p = ABSPATH . 'wp-admin/includes/admin.php';
$upload = new urm_frontend_upload($p);
$upload->upload();
print_r($upload->message);
}
?>
<!-- The Image Upload Form -->
<ul id="image-upload">
<form class="image-upload" id="file-form" enctype="multipart/form-data" action="<?php the_permalink(); ?>" method="POST">
<li id="async-upload-wrap">
<label for="async-upload">Upload</label>
<input type="file" id="async-upload" name="async-upload[]" multiple="true"> <input type="submit" value="Upload" name="html-upload" >
</li>
<li>
<input type="hidden" name="post_id" id="post_id" value="1199" />
<?php wp_nonce_field('client-file-upload'); ?>
<input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" />
</li>
</form>
</ul>
<!-- End image upload form -->
</div><!-- end content -->
</div><!-- end main -->
<?php get_footer(); ?>