wordpress wp_handle_upload not moving the file - wordpress

Can someone tell me why this function is not moving the uploaded files anywhere.
function handle_logo_upload($option){
if(!function_exists('wp_handle_upload'))
{
require_once(ABSPATH .'wp-admin/includes/file.php');
}
if(!empty($_FILES["site_logo_custom"])){
$theFile=$_FILES["site_logo_custom"];
$overrides=array('test_form'=>false);
$urls=wp_handle_upload($theFile,$overrides);
$temp=$urls["url"];
return $temp;
}
return $option;
}
I can't really find too much about wp_handle_upload function.
Thankss!!!

I assume your form is formatted kinda like this :
form action="" enctype="multipart/form-data" method="post"> //action is current post
<input type="file" name="file">
<input type="submit" name="submit">
</form>
And to upload the file to the wordpress upload folder using wp_handle_upload(); function you may use below code....
function handle_logo_upload($file){
require_once(ABSPATH.'wp-admin/includes/file.php');
$uploadedfile = $file;
$movefile = wp_handle_upload($uploadedfile, array('test_form' => false));
if ( $movefile ){
echo $movefile['url'];
//or return
return $movefile['url'];
}
}
if (isset($_POST['submit'])) {
handle_logo_upload($_FILES['file']);
}

Guessing that your function is called perfectly.
function handle_logo_upload($option){
if(!function_exists('wp_handle_upload'))
{
require_once(ABSPATH .'wp-admin/includes/file.php');
}
//you are using empty version make sure your php version is higher than 5.2
if(!empty($_FILES["site_logo_custom"])){
$move_logo = wp_handle_upload( $_FILES["site_logo_custom"], array('test_form' => false) );
if ( $move_logo && !isset($move_logo['error']) ) {
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($move_logo['file']),
'post_mime_type' => $move_logo['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename($move_logo['file']) ),
'post_content' => '',
'post_status' => 'inherit'
);
$logo_attach_id = wp_insert_attachment($attachment, $move_logo['file']);
$image_attributes = wp_get_attachment_image_src( $logo_attach_id );
if ( $image_attributes ) {
return $image_attributes[0];
}
else
{
return $option;
}
}else{
return $option;
}
}else{
return $option;
}
}
Please read my comments written in code

Related

Woocommerce Wordpress Adding Images to an Order in Cart

Here's the issue: I am trying to add multiple customer uploaded images to a woocommerce product order.
This is what my current function looks like to generate the fields before the add cart button (This displays properly and allows for a customer to select a file from their computer to upload):
function my_special_fields(){
if (get_the_title() == "My Special Product"){
echo '<table>
<tbody>
<tr>
<td>
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
</td>
</tr>
</tbody>
</table>';
}
}
Which I call with the hook:
add_filter('woocommerce_before_add_to_cart_button', 'my_special_fields');
I then use another hook for adding the item data to the cart:
add_action( 'woocommerce_add_cart_item_data', 'save_my_special_fields', 10, 2 );
And the function called with that hook looks like this:
function save_my_special_fields( $cart_item_data, $product_id ) {
// I save a lot of fields in here that are working fine so ignoring those for now
// This is where I try and find my file to upload
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = upload_user_file( $file );
}
}
}
}
It calls this piece of code I found for uploading files into wordpress: https://hugh.blog/2014/03/20/wordpress-upload-user-submitted-files-frontend/
function upload_user_file( $file = array() ) {
require_once( ABSPATH . 'wp-admin/includes/admin.php' );
$file_return = wp_handle_upload( $file, array('test_form' => false ) );
if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
return false;
} else {
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $file_return['url']
);
$attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
if( 0 < intval( $attachment_id ) ) {
return $attachment_id;
}
}
return false;
}
Right now I am not assigning to any post or doing anything with the image other than trying to get it to upload so that as an Admin I can view it in my media folder.
I think the issue is that the woocommerce form for the add to cart fields might not have this encoding:
enctype="multipart/form-data
Any help on implementing this without getting additional woocommerce plugins would be much appreciated.

Upload multiple images to a Woocommerce product

I am trying to upload various images from an URL to a given woocommerce product. The issue I am facing with my code is that, although I see that the images are being uploaded to the server, when I go to see my post I only see the last image uploaded to the gallery.
Here is my code:
function generateSecondImage($image_url, $post_id)
{
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $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, $file, $post_id);
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
$res3 = update_post_meta($post_id, '_product_image_gallery', $attach_id);
}
And here is how I call the function
for ($j=1; $j <$picCount ; $j++) {
generateSecondImage($pic[$j]->url, $post_id);
}
I am thinking that maybe, res3 is overwriting the gallery and showing only the last image posted, but if that is the case, how would I tell wordpress to include all of the images in the for loop?
Finally managed to solve it!
Here is my final code. My upload function goes like this:
function generateSecondImage($image_url, $post_id)
{
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents($file, $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, $file, $post_id);
require_once ABSPATH . 'wp-admin/includes/image.php';
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
$res1 = wp_update_attachment_metadata($attach_id, $attach_data);
echo "Attach ID is".$attach_id;
return $attach_id;
}
And then I had to create a comma-separated list of the IDs and add it to the add_post_meta
So my loop changed to this:
for ($j=1; $j <$picCount ; $j++) {
$attarray[] = generateSecondImage($pic[$j]->url, $post_id);
}
$commaList = implode(', ', $attarray);
$res3 = add_post_meta($post_id, '_product_image_gallery', $commaList);
Hope this helps anyone else looking for a solution.

Wordpress Deleting downloaded images on metabox with file

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 );
$count_files = count( $_FILES['my_files'] );
$uploads = wp_upload_dir();
foreach ( range( 0, $count_files ) as $i ) {
// create an array of the $_FILES for each file
$file_array = array(
'name' => $_FILES['files']['name'][$i],
'type' => $_FILES['files']['type'][$i],
'tmp_name' => $_FILES['files']['tmp_name'][$i],
'error' => $_FILES['files']['error'][$i],
'size' => $_FILES['files']['size'][$i],
);
// check to see if the file name is not empty
if ( !empty( $file_array['name'] ) ) {
// upload the file to the server
$uploaded_file = wp_handle_upload( $file_array, $upload_overrides );
// checks the file type and stores in in a variable
$wp_filetype = wp_check_filetype( basename( $uploaded_file['file'] ), null );
if ( $uploaded_file && !isset( $uploaded_file['error'] ) ) {
$ufiles = get_post_meta( $post_id, 'my_files', true );
if( empty( $ufiles ) ) $ufiles = array();
$ufiles[] = $uploaded_file;
update_post_meta( $post_id, 'my_files', $ufiles );
}
}
}
I am able to download files to metabox thanks to this code.
Output of the database is looks like what i show in the below
a:2:{i:0;a:3:{s:4:"file";s:48:"D:xampphtdocswp/wp-content/uploads/2016/08/2.jpg";s:3:"url";s:52:"http://localhost/wp/wp-content/uploads/2016/08/2.jpg";s:4:"type";s:10:"image/jpeg";}i:1;a:3:{s:4:"file";s:59:"D:xampphtdocswp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:3:"url";s:63:"http://localhost/wp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:4:"type";s:10:"image/jpeg";}}
I want to delete the images that i dont want with delete_post_meta method while i am selecting checkboxes on my update page.
$galleri = get_post_meta($id,'my_files',true);
<div class="galeri">
<?php
foreach($galleri as $galeri){
echo "<div style='margin:10px;display:inline-block;'><input type='checkbox' name='car_image_delete[]' value='".$galeri['url']."' /><img src='".$galeri['url']."' width='150' height='150'/></div>";
}
?>
</div>
I appreciate if you help me
Try this:
Use update_post_meta() function instead of delete_post_meta().
While using delete_post_meta(), it will delete custom fields.
So if you want to delete particular one file. You need to use update_post_meta().
$string = 'a:2:{i:0;a:3:{s:4:"file";s:48:"D:xampphtdocswp/wp-content/uploads/2016/08/2.jpg";s:3:"url";s:52:"http://localhost/wp/wp-content/uploads/2016/08/2.jpg";s:4:"type";s:10:"image/jpeg";}i:1;a:3:{s:4:"file";s:59:"D:xampphtdocswp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:3:"url";s:63:"http://localhost/wp/wp-content/uploads/2016/08/2da83a4s-960.jpg";s:4:"type";s:10:"image/jpeg";}}';
$arr = unserialize($string); //USE get_post_meta() function instead of
$index = array_search('http://localhost/wp/wp-content/uploads/2016/08/2da83a4s-960.jpg',array_column( $arr, 'url')); //search index
echo $index;
if (array_key_exists($index,$arr))
{
unset($arr[$index]); //remove array index
}
print_r($arr); //array with only value.
//use array_values() to reindex
update_post_meta($post_id, 'my_files', $arr); //update post meta

Wordpress upload frontend form not uploading images

I'm working on a frontend form in wordpress to create a custom post type and upload a picture attached to that post.
Below is my code so far. The post is created, but problem is that the images are not uploaded to the server either attached to that post. On the other hand I would like the images to be pre-visualized before sending the form, in the same way wordpress works for the admin area.
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['new_cpt_action'] ) && $_POST['new_cpt_action'] == "new_cpt" && isset( $_POST['new_cpt-form'] ) && wp_verify_nonce( $_POST['new_cpt-form'], 'create_new_cpt' ) ){
if (isset($_POST['submit'])) {
$error = "";
if (!empty($_POST['s_name'])) {
$s_name = $_POST['s_name'];
} else {
$error = 'Please insert a name';
}
if (empty($error)) {
$new_post = array(
'post_title' => $s_name,
'post_status' => 'pending',
'post_type' => 'my_cpt',
);
//Save the post
$post_id = wp_insert_post($new_post);
if( ! empty( $_FILES ) ) {
foreach( $_FILES as $file ) {
if( is_array( $file ) ) {
$attachment_id = wp_insert_attachment($file, $post_id);
}
}
}
//Redirect to the new post
if ( $post_id ) {
wp_redirect(home_url('site/'.$post_id));
exit;
}
}
}
}
And the form:
<form id="new_post" name="new_post" method="post" action="" class="" enctype="multipart/form-data">
<input type="text" id="s_name" name="s_name"/>
<input type="file" name="s_image" id="s_image" tabindex="25" />
<input type="submit" value="Create post and upload image" id="submit" name="submit"/>
<input type="hidden" id="new_cpt_action" name="new_cpt_action" value="new_cpt" />
</form>
If you could please let me know what I'm missing would be great.
Thanks
I managed to include the attachments in the wp media library with this code:
if ( $_FILES ) {
$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 );
}
}
}
}
Which calls the function frontend_handle_attachment:
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;
}
This works fine with a simple input in the form as follows:
<input type="file" name="file[]" multiple="multiple" />
As for the progress bar and pre-visualization of the images, I'm trying to implement dropzone, but no luck so far. At least the simple approach works.

Plugin Development - wp insert post not working

I am new to plugin development for WP. I have a problem with wp_insert_post from the plugin file, tested running this plugin php file, and all the code before the wp_insert_post is fine, but once it jumps on wp_insert_post nothing happens after, stuck at 'Test15'. Tested running the insert post part of the code from test page within the theme folder and it worked. Not sure what is the problem here. Please see the code below.
function db_importer_insert_properties($properties, $category, $user_id, $post_type) {
echo 'Test9<br>';
$result = true;
echo 'Test10<br>';
if($properties) {
echo 'Test11<br>';
if(count($properties) > 0) {
echo 'Test12<br/>';
print_r($properties);
echo '<br/>';
$count = 0;
foreach($properties as $property) {
echo 'Test13<br/>';
$address =$property['address'] ; //get title
$building=$address['streetNumber'];
$street=$address['street'];
$suburb=$address['suburb'];
$state=$address['state'];
$postcode=$address['postcode'];
$title=$building. ' ' .$street.', '.$suburb.', '.$postcode.', '.strtoupper($state);
//test post
$new_post = array(
'post_title' => 'My post10 ',
'post_content' => 'This is my post10 ',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => 'uncategorized'
);
echo 'Test14<br/>';
print_r($new_post);
echo '<br/>';
echo 'Test15<br/>';
wp_insert_post($new_post);
echo 'Test16<br>';
if($post_id != 0) {
add_post_meta($post_id, "_bathrooms", esc_attr($property['features']['bathrooms']));
add_post_meta($post_id, "_bedrooms", esc_attr($property['features']['bedrooms']));
if(is_array($property['images'])) {
add_post_meta($post_id, "_images", esc_attr(implode("\n", $property['images'])));
}
else {
feedback("Post ID was 0");
}
feedback("added property $title with post_id $post_id");
$count++;
}
else {
feedback("post was failed to add");
}
}
feedback("Added $count properties");
}
else {
feedback("No properties to add.");
}
}
else {
feedback("No properties were selected");
$result = false;
}
return $result;
}
You forgot to declare your $post_id variable. Use the following:
$post_id = wp_insert_post( $new_post, true );
This will return the post ID on success or a WP error on failure.
Use print_r( $post_id ) to check the result.

Resources