<strong>Update</strong> : <em>Just to let everybody know that gentleman @Dbranes has been helping me out and have almost solved the issue. I am currently testing in different environments to rule out last few bugs. Million thanks to distinguished gentlemen below who suggested various other solutions.</em>
Hello guys,
Am new here and Just to be honest it is not a question I need to ask but a requirement for a few lines of code probably.
<strong>Situation</strong> : I have recently bought a plugin 'Ajax image upload for wp' from codecanyon. The plugin is based off of flash version of [[LINK href="http://www.uploadify.com/"]]uploadify[[/LINK]]. It's aim is to allow multiple uploads from the wordpress frontend, and offers various configs. I have integrated the plugin into a form as shown here in the [[LINK href="http://quanticalabs.com/quanticawp/ajax-multi-upload/"]]examples 4 and 5[[/LINK]]. If you must know it is a simple from to create posts from front-end and the code is provided below. Here is a [[LINK href="http://postimg.org/image/57xjbn8gj/"]]snapshot of the form test page[[/LINK]].
<strong>Requirement</strong> - The plugin works flawless and the images are currently uploaded to wp media-library folders. The issue is I <em>need images to be attached along with the post that is being created</em>. The upload process is handled by a upload.php page, a url to which is given within the form tag as you can see below. Contents of the upload.php is pasted below in the third block of code.
P.S - If you need to take a look at other associated files of the plugin please provide me your email or suggest me a way to send you those files in private. Out of respect for the plugin developer I cannot use the pastebins for other files.
A sample form tag for the plugin which provides a flash upload button in front-end.
<input type='file' class='AMU' uploadScript='http://localhost/testsite/wp-content/plugins/ajax_multi_upload/upload.php' startOn='auto' multi='true' maxSize='204800' />
Below is what my form code within a template inlcuding minor validations and stuff. It is a no fancy simple form and the concerned upload field in the line 118.
<?php
/*
Template Name: Rate Wine Form
*/
?>
<?php //validations before the header
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['title'])) {
$title = $_POST['title'];
} else {
$error .= "Please add a title<br />";
}
if (!empty($_POST['description'])) {
$description = $_POST['description'];
} else {
$error .= "Please add a description<br />";
}
if (!empty($_POST['winerating'])) {
$post_tags = $_POST['winerating'];
} else {
$error .= "Please add some keywords<br />";
}
//Defining variables
$tags = $_POST['post_tags'];
$winerating = $_POST['winerating'];
// ADD THE FORM INPUT TO $new_post ARRAY
if (empty($error)) {
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post', //'post',page' or use a custom post type if you want to
'rating' => $winerating
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
//KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
wp_set_post_tags($pid, $_POST['post_tags']);
//SET POST TERM - CATEGORY
wp_set_post_terms($pid,(array)($_POST['cat']),'category',true);
//ADD OUR CUSTOM FIELDS
add_post_meta($pid, 'rating', $winerating, true);
} // END SAVING POST
} // END VALIDATION
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
wp_insert_post('new_post');
?>
<?php get_header(); ?>
<div id="container">
<div id="content" role="main">
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1><?php the_title();?></h1>
<?php the_content(); ?>
<?php
if (!empty($error)) {
echo '<p class="error"><strong>Your message was NOT sent<br/> The following error(s) returned:</strong><br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo '<p class="success">' . $success . '</p>';
}
?>
<!-- WINE RATING FORM -->
<div class="wpcf7">
<form id="new_post" name="new_post" method="post" action="" class="wpcf7-form" enctype="multipart/form-data">
<!-- post name -->
<fieldset name="name">
<label for="title">Wine Name:</label>
<input type="text" id="title" value="" tabindex="5" name="title" />
</fieldset>
<!-- post Category -->
<fieldset class="category">
<label for="cat">Type:</label>
<?php wp_dropdown_categories( 'tab_index=10&taxonomy=category&hide_empty=0' ); ?>
</fieldset>
<!-- post Content -->
<fieldset class="content">
<label for="description">Description and Notes:</label>
<textarea id="description" tabindex="15" name="description" cols="80" rows="10"></textarea>
</fieldset>
<!-- wine Rating -->
<fieldset class="winerating">
<label for="winerating">Your Rating</label>
<input type="text" value="" id="winerating" tabindex="20" name="winerating" />
</fieldset>
<fieldset name="upload">
<label for="upload-image" class="label">UPLOAD IMAGES</label>
<input type='file' class='AMU' uploadScript='http://localhost/testsite/wp-content/plugins/ajax_multi_upload/upload.php' startOn='auto' multi='true' maxSize='204800' />
</fieldset>
<fieldset class="submit">
<input type="submit" value="Post Review" tabindex="40" id="submit" name="submit" />
</fieldset>
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form><!-- END OF FORM -->
</div> <!-- END WPCF7 -->
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Below is a code for the upload.php that was provided with the plugin.
<?php
error_reporting(0);
if($_POST["PHPSESSID"]!="")
{
session_id($_POST["PHPSESSID"]);
//session_name("your_session_name"); uncomment this if your session has a name
session_start();
}
if($_POST["action"]=="upload")
{
if(!empty($_FILES))
{
$result = array();
$tempFile = $_FILES["Filedata"]["tmp_name"];
require_once("../../../wp-config.php");
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
$wp->send_headers();
$uploadsInfo = wp_upload_dir();
$targetPath = "../../uploads" . $uploadsInfo["subdir"] . "/";
$pathinfo = pathinfo($_FILES['Filedata']['name']);
$fileExt = $pathinfo["extension"];
//if($fileExt!="php" && $fileExt!="php5" && $fileExt!="php4" && $fileExt!="php3" && $fileExt!="html" && $fileExt!="htm" && $fileExt!="js")//if you want to prevent from upload the files with given extensions uncomment this line
//{//if you want to prevent from upload the files with given extensions uncomment this line
$fileName = stripslashes($pathinfo["filename"])/* . time()*/;
$targetFile = $targetPath . $fileName . "." . $fileExt;
$realPath = realpath($targetPath);
$documentRoot = realpath($_SERVER["DOCUMENT_ROOT"]);
$realTargetPath = str_replace($documentRoot, "", $realPath) . "/";
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
//echo $realTargetPath;
//if(move_uploaded_file($tempFile, $targetFile))
$overrides = array( 'test_form' => false );
//move image to the WP defined upload directory and set correct permissions
if($_POST["thumbnails"]!="")
{
$thumbnailsExplode = explode(",", $_POST["thumbnails"]);
if($_POST["thumbnailsCrop"]!="")
$thumbnailsCropExplode = explode(",", $_POST["thumbnailsCrop"]);
for($i=0; $i<count($thumbnailsExplode); $i++)
{
$dimensions = explode("x", trim($thumbnailsExplode[$i]));
add_image_size('amu_thumbnail_' . $i, (int)$dimensions[0], (int)$dimensions[1], ($thumbnailsCropExplode[$i]=="true" ? true : false));
}
}
if($file = wp_handle_upload($_FILES["Filedata"], $overrides ))
{
$pathinfo = pathinfo($file["url"]);
$targetFile = $pathinfo["dirname"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"];
$image = wp_get_image_editor($uploadsInfo["path"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"]);
//error_log($uploadsInfo["path"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"] , 3, "log.txt");
$image->resize(700, null, true);
$image->save($uploadsInfo["path"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"]);
/*//watermark
$watermarks = array();
$i = 0;
while($_POST["watermark_path".$i]!="")
{
$watermarks[$i]["path"] = $_POST["watermark_path".$i];
$watermarks[$i]["bottom"] = $_POST["watermark_bottom".$i];
$watermarks[$i]["right"] = $_POST["watermark_right".$i];
$i++;
}
if(count($watermarks))
{
require_once("functions.php");
$imagesize = getimagesize($targetFile);
$width = $imagesize[0];
$height = $imagesize[1];
resizeImage($width, $height, $targetFile, $targetFile, $watermarks);
}*/
$wp_filetype = wp_check_filetype(basename($realTargetPath . $fileName . "." . $fileExt), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($realTargetPath . $fileName . "." . $fileExt)),
'post_content' => '',
'post_status' => 'inherit',
'post_author' => $_POST["userId"]
);
if((int)$_POST["postId"]>0 && $_POST["attachimages"]=="currentPost")
$attach_id = wp_insert_attachment( $attachment, $file["file"], (int)$_POST["postId"] );
else
$attach_id = wp_insert_attachment( $attachment, $file["file"], null );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file["file"] );
wp_update_attachment_metadata( $attach_id, $attach_data );
//generate thumbnails after the main file is uploaded
if($_POST["thumbnails"]!="")
{
$result["thumbnails"] = array();
for($i=0; $i<count($thumbnailsExplode); $i++)
{
$result["thumbnails"][] = (isset($attach_data["sizes"]['amu_thumbnail_' . $i]["file"]) ? $attach_data["sizes"]['amu_thumbnail_' . $i]["file"] : $pathinfo["filename"] . "." . $pathinfo["extension"]);
}
}
}
else
$result["error"] .= " Upload failed!";
/*}
else
$result["error"] .= " Cannot upload " . $fileExt . " files!";
//if you want to prevent from upload the files with given extensions uncomment this block
*/
$current_user = wp_get_current_user();
$result["userID"] = $current_user->ID;
$result["path"] = $pathinfo["dirname"] . "/";
$result["filename"] = $pathinfo["filename"] . "." . $pathinfo["extension"];
$result["extension"] = $pathinfo["extension"];
$result["attach_id"] = $attach_id;
/*$result["path"] = $realTargetPath;
$result["filename"] = $fileName . "." . $fileExt;
$result["extension"] = $fileExt;
$result["attach_id"] = $attach_id;*/
echo json_encode($result);
exit();
}
}
else if($_POST["action"]=="remove")
{
require_once("../../../wp-config.php");
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
$wp->send_headers();
$uploadsInfo = wp_upload_dir();
$targetPath = "../../uploads" . $uploadsInfo["subdir"] . "/";
$message = "";
wp_delete_attachment($_POST["attach_id"]);
echo $message;
//$message = "";
/*if you uploading files to other than files directory, you've got to change it in three below lines
in function pathinfo, in if statement and in unlink function*/
/*$pathInfo = pathinfo("files/".stripslashes($_POST["filename"]));
if($pathInfo['dirname']=="files")
{
if(!@unlink("files/".stripslashes($_POST["filename"])))
$message = "Error - file not found! ";
}
else
$message = "Security error!";
echo $message;*/
}
?>
Remy answers:
Editing my answer now after looking at the code. It seems like the attachment to the post parent can be handled, if you pass a "postId" key in the POST array of the form, the key's value being the post id created by WP after submitting the form. How to do that depends on how is handled the creation of the post after submission.
33 comments:
Hey @Remy, Question updated with the code. Just looking for a quick fix at the moment. Whilst modifying please keep in mind that the rest of the functionality of the plugin remains intact. Appreciate your interest.
33 comments:
@Remy, sorry for the delay to revert back. I posted the requirement very late at night y'day and went to sleep. For more clarity I have now edited my question and provided the code for the form too so that you guys get a better perspective. Now you know how the creation of the post is handled please let me know of a solution.
Remy comments:
I still feel like there is something missing. Any javascript file used that you could show us ? The $pid created in your form handling part should be passed to upload.php to set the post parent of the images
33 comments:
@Remy, there are two more files in php within the plugin folder. Ajax_multi_upload.php and functions.php and four other js files. Now, how do I send these files to you to take a look. In respect of the plugin developer I do not want to use pastebins.
33 comments:
@Remy, Please check your email. I have sent you the files.
Dbranes answers:
Maybe you could post the result from
print_r( $_REQUEST );
located in the processing part of your main form (where you create the post) and we could see if you got any <strong>attach_id</strong>
To link attachment to a post in general, you can use
if( $post_id > 0 && $attachment_id > 0 )
wpquestions8452_attachment2post( $post_id, $attachment_id );
where
function wpquestions8452_attachment2post( $post_id, $attachment_id ){
global $wpdb;
$sql = "UPDATE {$wpdb->posts} SET post_parent = %d WHERE ID = %d AND post_type = 'attachment'";
return $wpdb->query( $wpdb->prepare( $sql, $post_id, $attachment_id ) );
}
33 comments:
@Dbranes. I did not get what you meant by your first code. However I have updated my question with codes to both the form and the upload.php. Probably now you can tell me how I apply suggested codes.
Cheers..
Dbranes comments:
Here is one idea:
Generate a key in the main form, maybe like this:
<?php $key = "key_".substr(md5(time()), 0, 10); ?>
it will give you a string like <strong>key_f0165d1c5b</strong>.
Then you will have to include this key in the upload script url as an GET parameter:
<input type='file' class='AMU' uploadScript='http://localhost/testsite/wp-content/plugins/ajax_multi_upload/upload.php?key=<?php echo $key; ?>' startOn='auto' multi='true' maxSize='204800' />
Then add a hidden input field to the main form with the key value:
<input type="hidden" name="key" value="<?php echo $key; ?>" />
So the idea is to let the upload script store the attachments id's into the database (or a cookie or a session) with the relevant key.
Then after the part where you process <em>wp_insert_post()</em> you can fetch the corresponding key value (containing the attachments id's array) and then match the attachments to the newly inserted post with the above <em>wpquestions8452_attachment2post()</em> function.
If you want to store the key in the database, you could for example use the transients API.
Here is an example how you can store an array:
$a = array(11,22,33);
set_transient($key, $a , 60*60);
here is an example how you can fetch it:
$b = get_transient($key);
print_r($b);
?>
You can then control the <em>time-to-live</em>, which is set to <em>60*60</em> seconds above.
So this is my idea ;-)
33 comments:
@Dbranes, Kindly check your mail.
Hariprasad Vijayan answers:
Hello,
If image uploader works well and uploads image into media library, then your upload function will return file path/details. You are able to create post in your front end i hope it also works fine. I think attaching the uploaded file with the post is your problem. For this you can use the following wordpress function.
<?php wp_insert_attachment( $attachment, $filename, $parent_post_id ); ?>
You can use the above function after creating the post, I think you used the following method for creating post.
$pid = wp_insert_post($new_post);
This will return the post id. You can use this post id as parent_post_id in wp_insert_attachment()
Check the following link for further reference
http://codex.wordpress.org/Function_Reference/wp_insert_attachment
Hope this will help you...
Good luck
33 comments:
@Hariprasad, I have updated my question with the codes to form and upload.php both. Please take a look and let me know where I can apply the changes you suggested.
Cheers..
Hariprasad Vijayan comments:
Hello,
Add the following code after
//SAVE THE POST
$pid = wp_insert_post($new_post);
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit'
);
wp_insert_attachment( $attachment, $filename, $pid );
$attachment mentioned above, $filename is your uploaded filename that receiving in $_POST(Change it with your value. use print_r($_POST) to get all values receiving in $_POST). $pid is most id, will get after creating post
Good luck
33 comments:
@Hariprasad - Disclaimer - I am no good in php so I pasted the code as it is. And the image upload threw some IOerror. I suppose I was suppose to change someting in the suggested code but I didnot get what? Could you please be kind and elaborate.
Link to [[LINK href="http://postimg.org/image/5304fl94f/"]]snapshot of error[[/LINK]].
33 comments:
I put the print_r($_POST) after wp_insert_post('new_post'); and I get the following following and I can see that it has completely skipped the image upload :(
Array ( [title] => title for the test only [cat] => 2 [description] => some lorem ipsum text in content body as description [winerating] => 7 / 10 [submit] => Post Review [action] => new_post [_wpnonce] => 64753dcd0b [_wp_http_referer] => /testsite/minimal-form-test/ )
33 comments:
@Hariprasad, I am not able to edit my last response to you ( due to a "500 Internal Server Error" which is weird considering such an awesome site) so I will say it here. Although the code you suggested threw and HTTP error on the upload but the post that was created contained a blank attachment which I saw in the media-library was attached to the post. ARE we on the right track ? I am so excited right now. Lol
Hariprasad Vijayan comments:
Hello,
Sorry for the delay. I didn't get any idea from the $_POST printed output. My email id is [email protected]. You can send files to it. i need FTP access to check the functionality of upload plugin.
Hariprasad Vijayan comments:
Hello,
Got solution. Change the following files
Template
<?php
/*
Template Name: Rate Wine Form
*/
?>
<?php //validations before the header
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['title'])) {
$title = $_POST['title'];
} else {
$error .= "Please add a title<br />";
}
if (!empty($_POST['description'])) {
$description = $_POST['description'];
} else {
$error .= "Please add a description<br />";
}
if (!empty($_POST['winerating'])) {
$post_tags = $_POST['winerating'];
} else {
$error .= "Please add some keywords<br />";
}
//Defining variables
$tags = $_POST['post_tags'];
$winerating = $_POST['winerating'];
// ADD THE FORM INPUT TO $new_post ARRAY
if (empty($error)) {
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => array($_POST['cat']), // Usable for custom taxonomies too
'tags_input' => array($tags),
'post_status' => 'publish', // Choose: publish, preview, future, draft, etc.
'post_type' => 'post', //'post',page' or use a custom post type if you want to
'rating' => $winerating
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
//KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
wp_set_post_tags($pid, $_POST['post_tags']);
if($_POST['tmp_id'])
{
global $wpdb;
$wpdb->query("UPDATE $wpdb->posts SET post_parent = ".$pid." WHERE post_parent=".$_POST['tmp_id']." AND post_type = 'attachment'");
}
//SET POST TERM - CATEGORY
wp_set_post_terms($pid,(array)($_POST['cat']),'category',true);
//ADD OUR CUSTOM FIELDS
add_post_meta($pid, 'rating', $winerating, true);
} // END SAVING POST
} // END VALIDATION
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
wp_insert_post('new_post');
?>
<?php get_header(); ?>
<div id="container">
<div id="content" role="main">
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h1><?php the_title();?></h1>
<?php the_content(); ?>
<?php
if (!empty($error)) {
echo '<p class="error">Your message was NOT sent<br/> The following error(s) returned:<br/>' . $error . '</p>';
} elseif (!empty($success)) {
echo '<p class="success">' . $success . '</p>';
}
?>
<?php $tmp_id=rand(); ?>
<!-- WINE RATING FORM -->
<div class="wpcf7">
<form id="new_post" name="new_post" method="post" action="" class="wpcf7-form" enctype="multipart/form-data">
<!-- post name -->
<fieldset name="name">
<label for="title">Wine Name:</label>
<input type="text" id="title" value="" tabindex="5" name="title" />
</fieldset>
<!-- post Category -->
<fieldset class="category">
<label for="cat">Type:</label>
<?php wp_dropdown_categories( 'tab_index=10&taxonomy=category&hide_empty=0' ); ?>
</fieldset>
<!-- post Content -->
<fieldset class="content">
<label for="description">Description and Notes:</label>
<textarea id="description" tabindex="15" name="description" cols="80" rows="10"></textarea>
</fieldset>
<!-- wine Rating -->
<fieldset class="winerating">
<label for="winerating">Your Rating</label>
<input type="text" value="" id="winerating" tabindex="20" name="winerating" />
</fieldset>
<fieldset name="upload">
<label for="upload-image" class="label">UPLOAD IMAGES</label>
<input type='file' class='AMU' uploadScript='http://localhost/testsite/wp-content/plugins/ajax_multi_upload/upload.php?tmp_id=<?php echo $tmp_id; ?>' startOn='auto' multi='true' maxSize='2048000' />
</fieldset>
<fieldset class="submit">
<input type="submit" value="Post Review" tabindex="40" id="submit" name="submit" />
</fieldset>
<input type="hidden" name="tmp_id" value="<?php echo $tmp_id; ?>" />
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form><!-- END OF FORM -->
</div> <!-- END WPCF7 -->
<?php endwhile; // end of the loop. ?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Upload.php
<?php
error_reporting(0);
if($_POST["PHPSESSID"]!="")
{
session_id($_POST["PHPSESSID"]);
//session_name("your_session_name"); uncomment this if your session has a name
session_start();
}
if($_POST["action"]=="upload")
{
if(!empty($_FILES))
{
$result = array();
$tempFile = $_FILES["Filedata"]["tmp_name"];
require_once("../../../wp-config.php");
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
$wp->send_headers();
$uploadsInfo = wp_upload_dir();
$targetPath = "../../uploads" . $uploadsInfo["subdir"] . "/";
$pathinfo = pathinfo($_FILES['Filedata']['name']);
$fileExt = $pathinfo["extension"];
//if($fileExt!="php" && $fileExt!="php5" && $fileExt!="php4" && $fileExt!="php3" && $fileExt!="html" && $fileExt!="htm" && $fileExt!="js")//if you want to prevent from upload the files with given extensions uncomment this line
//{//if you want to prevent from upload the files with given extensions uncomment this line
$fileName = stripslashes($pathinfo["filename"])/* . time()*/;
$targetFile = $targetPath . $fileName . "." . $fileExt;
$realPath = realpath($targetPath);
$documentRoot = realpath($_SERVER["DOCUMENT_ROOT"]);
$realTargetPath = str_replace($documentRoot, "", $realPath) . "/";
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
//echo $realTargetPath;
//if(move_uploaded_file($tempFile, $targetFile))
$overrides = array( 'test_form' => false );
//move image to the WP defined upload directory and set correct permissions
if($_POST["thumbnails"]!="")
{
$thumbnailsExplode = explode(",", $_POST["thumbnails"]);
if($_POST["thumbnailsCrop"]!="")
$thumbnailsCropExplode = explode(",", $_POST["thumbnailsCrop"]);
for($i=0; $i<count($thumbnailsExplode); $i++)
{
$dimensions = explode("x", trim($thumbnailsExplode[$i]));
add_image_size('amu_thumbnail_' . $i, (int)$dimensions[0], (int)$dimensions[1], ($thumbnailsCropExplode[$i]=="true" ? true : false));
}
}
if($file = wp_handle_upload($_FILES["Filedata"], $overrides ))
{
$pathinfo = pathinfo($file["url"]);
$targetFile = $pathinfo["dirname"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"];
$image = wp_get_image_editor($uploadsInfo["path"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"]);
//error_log($uploadsInfo["path"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"] , 3, "log.txt");
$image->resize(700, null, true);
$image->save($uploadsInfo["path"] . "/" . $pathinfo["filename"] . "." . $pathinfo["extension"]);
/*//watermark
$watermarks = array();
$i = 0;
while($_POST["watermark_path".$i]!="")
{
$watermarks[$i]["path"] = $_POST["watermark_path".$i];
$watermarks[$i]["bottom"] = $_POST["watermark_bottom".$i];
$watermarks[$i]["right"] = $_POST["watermark_right".$i];
$i++;
}
if(count($watermarks))
{
require_once("functions.php");
$imagesize = getimagesize($targetFile);
$width = $imagesize[0];
$height = $imagesize[1];
resizeImage($width, $height, $targetFile, $targetFile, $watermarks);
}*/
$wp_filetype = wp_check_filetype(basename($realTargetPath . $fileName . "." . $fileExt), null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($realTargetPath . $fileName . "." . $fileExt)),
'post_content' => '',
'post_status' => 'inherit',
'post_author' => $_POST["userId"]
);
if((int)$_POST["postId"]>0 && $_POST["attachimages"]=="currentPost")
$attach_id = wp_insert_attachment( $attachment, $file["file"], (int)$_POST["postId"] );
else
$attach_id = wp_insert_attachment( $attachment, $file["file"], $_GET['tmp_id'] );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file["file"] );
wp_update_attachment_metadata( $attach_id, $attach_data );
//generate thumbnails after the main file is uploaded
if($_POST["thumbnails"]!="")
{
$result["thumbnails"] = array();
for($i=0; $i<count($thumbnailsExplode); $i++)
{
$result["thumbnails"][] = (isset($attach_data["sizes"]['amu_thumbnail_' . $i]["file"]) ? $attach_data["sizes"]['amu_thumbnail_' . $i]["file"] : $pathinfo["filename"] . "." . $pathinfo["extension"]);
}
}
}
else
$result["error"] .= " Upload failed!";
/*}
else
$result["error"] .= " Cannot upload " . $fileExt . " files!";
//if you want to prevent from upload the files with given extensions uncomment this block
*/
$current_user = wp_get_current_user();
$result["userID"] = $current_user->ID;
$result["path"] = $pathinfo["dirname"] . "/";
$result["filename"] = $pathinfo["filename"] . "." . $pathinfo["extension"];
$result["extension"] = $pathinfo["extension"];
$result["attach_id"] = $attach_id;
/*$result["path"] = $realTargetPath;
$result["filename"] = $fileName . "." . $fileExt;
$result["extension"] = $fileExt;
$result["attach_id"] = $attach_id;*/
echo json_encode($result);
exit();
}
}
else if($_POST["action"]=="remove")
{
require_once("../../../wp-config.php");
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
$wp->send_headers();
$uploadsInfo = wp_upload_dir();
$targetPath = "../../uploads" . $uploadsInfo["subdir"] . "/";
$message = "";
wp_delete_attachment($_POST["attach_id"]);
echo $message;
//$message = "";
/*if you uploading files to other than files directory, you've got to change it in three below lines
in function pathinfo, in if statement and in unlink function*/
/*$pathInfo = pathinfo("files/".stripslashes($_POST["filename"]));
if($pathInfo['dirname']=="files")
{
if(!@unlink("files/".stripslashes($_POST["filename"])))
$message = "Error - file not found! ";
}
else
$message = "Security error!";
echo $message;*/
}
?>
It works perfectly here..
Good luck..
33 comments:
@Harinath. Code is flawless. I deeply appreciate the time you gave for this. I wish I had written the status update earlier so that you could save time. It just struck me later that I should announce this that my work is almost done so everybody else could focus on someone else's issue. I guess this should be brought into admin's attention. If only there was a status update field for the askers many people would save time, and nobody will argue with anyone who says "time is money".
Apart from that amazingly your code was bang on target the first time.
I am glad about my decision to give this platform a try.
What a wonderful community !
Arnav Joy answers:
do you want to attach the thumbnail to the same post where it is displayed ?
Arnav Joy comments:
the code which you have shown is handling uplaod process can you show full code of your template ?
you just have to pass a hidden variable with the post id to which you want to assign this uploaded media .
you can pass hidden input as
<input type="hidden" name="postId" value="101" />
where 101 is the post id to which you want to assign the attachment.
if you want to attach it to current post then use following
<input type="hidden" name="postId" value="<?php echo get_the_ID();?>" />
Arnav Joy comments:
check these modified files
upload.php
http://pastebin.com/WymdBGAR
and your template Rate Wine Form
http://pastebin.com/31JVkVVf
33 comments:
@Hariprasad, I have updated my question with the codes to form and upload.php both. Please take a look and let me know where I can apply the changes you suggested.
33 comments:
@arnav, Please ignore the earlier post. and yes I am working on you suggestion. Thank you for taking interest.
33 comments:
@arnav I took you the template as it is and created a new page. I took the modified upload.php and replaced the one in the plugin file with it. At the frontend the form and plugins upload button were rendered flawless but when I did a test submission/post there was no post created at all :(
Please take a look at the [[LINK href="http://postimg.org/image/57xjbn8gj/"]]form test page[[/LINK]].