Upload multiple images to a Woocommerce product - wordpress

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.

Related

move_uploaded_file() not working on wordpress front end

I have working code that uploads an image from the front end and sets it as a featured image and custom field photo for a custom post type but I am unable to figure out how to set the upload path.
Essentially if I have an employee I would like to use the custom field last_first to generate a folder path:
"wp-content/uploads/employee_mug/[last_first]/"
which would contain a photo of the employee. I require this as the folder structure is required for another page. The code is in my functions.php file but is simply in an if statement.
I've attempted to use move_uploaded_file with no success.
if (isset($_POST['last_first']) && is_user_logged_in()){
$my_post = array (
'post_type' => 'employee',
'post_status' => 'publish', // can also draft, private or publish
'post_title' => $_POST['last_first'],
);
$postID = wp_insert_post($my_post);
if (!function_exists('wp_generate_attachment_metadata')){
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
}
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$attach_id = media_handle_upload( $file, $postID );
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
update_field('date_of_birth', $_POST['dob'], $postID);
update_field('sex', $_POST['sex'], $postID);
die;}
I would like that when a file is attached the end result be:
"wp-content/uploads/employee_mug/[last_first]/1.jpg"
UPDATE 1.0
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
$path = "./wp-content/uploads/mug_shots/";
$path .= $name;
if ( wp_mkdir_p( $path ) ) {
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
} else {
wp_mkdir_p( $path );
$attach_id = media_handle_upload( $file, $postID );
move_uploaded_file($file, $path);
}
}
now checks to see if a folder was create and if not it will make one with the employee name but the move_uploaded file is not moving the photo into the generator folder. I simply need to find a way to make the file move to the generated folder at this point, Any help would be greatly appreciated!
UPDATE 2.0
the bellow code moves the file to wp-content/uploads/employee_mug/ but will not move it into the generated folder with the employee is name. I'm very close here I simply need the file moved into the employee is named folder at this point!
$name = $_POST['last_first'];
if ($_FILES) {
foreach ($_FILES as $file => $array) {
/*
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) {
return "upload error : " . $_FILES[$file]['error'];
}
*/
//for MKDIR FOR CREATION
$path = "./wp-content/uploads/employee_mug/";
$path .= $name;
//FOR MOVING UPLOADED IMAGE
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $name;
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}
if ( wp_mkdir_p( $path ) ) {
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
} else {
wp_mkdir_p( $path );
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['mug_shot'];
$upload_overrides = array( 'subjects_add' => false );
add_filter('upload_dir', 'my_upload_dir');
$attach_id = media_handle_upload( $file, $postID );
remove_filter('upload_dir', 'my_upload_dir');
/*
move_uploaded_file($file, $path);
$attach_id = media_handle_upload( $file, $postID );
*/
}
}
}
if ($attach_id > 0){
//and if you want to set that image as Post then use:
update_post_meta($postID,'_thumbnail_id',$attach_id);
}
////////////////////////////////////////////////////////////////////////////////////////////
//update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('last_first', $_POST['last_first'], $postID);
update_field('employee_mug', $attach_id, $postID);
UPDATE 3.0 SOLVED ******
function my_upload_dir($upload) {
$upload['subdir'] = '/employee_mug/' . $_POST['last_first'];
$upload['path'] = $upload['basedir'] . $upload['subdir'];
$upload['url'] = $upload['baseurl'] . $upload['subdir'];
return $upload;
}

How to generate multiple image with different size using rest api in wordpress

I want to generate multiple image when passed image url through rest api.
and serialize '_wp_attachment_metadata' data in postmeta table like thisa:5:{s:5:"width";i:1920;s:6:"height";i:1200;s:4:"file";s:29:"2018/05/Haute-Panoramic-1.jpg";s:5:"sizes";a:8:{s:9:"thumbnail";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-150x150.jpg";s:5:"width";i:150;s:6:"height";i:150;s:9:"mime-type";s:10:"image/jpeg";}s:6:"medium";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-300x188.jpg";s:5:"width";i:300;s:6:"height";i:188;s:9:"mime-type";s:10:"image/jpeg";}s:12:"medium_large";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-768x480.jpg";s:5:"width";i:768;s:6:"height";i:480;s:9:"mime-type";s:10:"image/jpeg";}s:5:"large";a:4:{s:4:"file";s:30:"Haute-Panoramic-1-1024x640.jpg";s:5:"width";i:1024;s:6:"height";i:640;s:9:"mime-type";s:10:"image/jpeg";}s:6:"slider";a:4:{s:4:"file";s:30:"Haute-Panoramic-1-1440x550.jpg";s:5:"width";i:1440;s:6:"height";i:550;s:9:"mime-type";s:10:"image/jpeg";}s:25:"real_estate_lite_property";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-400x300.jpg";s:5:"width";i:400;s:6:"height";i:300;s:9:"mime-type";s:10:"image/jpeg";}s:32:"real_estate_lite_property_slider";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-800x600.jpg";s:5:"width";i:800;s:6:"height";i:600;s:9:"mime-type";s:10:"image/jpeg";}s:27:"real_estate_lite_page_thumb";a:4:{s:4:"file";s:29:"Haute-Panoramic-1-400x220.jpg";s:5:"width";i:400;s:6:"height";i:220;s:9:"mime-type";s:10:"image/jpeg";}}s:10:"image_meta";a:12:{s:8:"aperture";s:1:"0";s:6:"credit";s:0:"";s:6:"camera";s:0:"";s:7:"caption";s:0:"";s:17:"created_timestamp";s:1:"0";s:9:"copyright";s:0:"";s:12:"focal_length";s:1:"0";s:3:"iso";s:1:"0";s:13:"shutter_speed";s:1:"0";s:5:"title";s:0:"";s:11:"orientation";s:1:"0";s:8:"keywords";a:0:{}}}
Here is the my code:-
$fetured_array=["https://media.architecturaldigest.com/photos/585811cfdcb583e908275f46/4:3/w_384/buildings-with-trees-001.jpg","https://media.architecturaldigest.com/photos/585811cfdcb583e908275f46/4:3/w_384/buildings-with-trees-001.jpg"]
$count_img=0;
foreach($feature_img as $url)
{
//$url = $feature_img;
$path = parse_url($url, PHP_URL_PATH);
$filename = mt_rand().basename($path);
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir['path'] . '/' . $filename;
$contents= file_get_contents($url);
$savefile = fopen($uploadfile, 'w');
chmod($uploadfile, 0777);
fwrite($savefile, $contents);
fclose($savefile);
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'ID'=>$page_id,
'post_mime_type' => $wp_filetype['type'],
'post_title' => $filename,
'post_content' => '',
'post_status' => 'inherit',
'post_parent'=>$new_post_id,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
if($count_img==0){
if ($attach_id) {
set_post_thumbnail( $new_post_id, $attach_id );
}
}
$newwidth = '250';
foreach ($attachment as $attached) {
$id = $attach_id;
$metadata = wp_get_attachment_metadata($id);
$metadata['width'] = $newwidth;
wp_update_attachment_metadata($id,$metadata);
}
array_push($fetured_array,$attach_id);
$count_img++;
}
$format_fetured_img=implode('|',$fetured_array);
update_post_meta($new_post_id, 'real_estate_property_images', $format_fetured_img);
Currently its working but only uploaded images into uploads/2018/5
folder with original size of the image. How can I upload image with
dynamic generate size as like when upload image in Media library by
wordpress admin
Please help me out to find the solution for the above.
Thanks in advance
Here is the solution.
First make sure you attached the image.php file just before the $fetured_array like this
require ( ABSPATH . 'wp-admin/includes/image.php' ); after that add thumbsize add_image_size( 'custom-size', 110, 100 );
Now after $attach_id = wp_insert_attachment( $attachment, $uploadfile ); add following two lines
$attach_data = wp_generate_attachment_metadata( $attach_id, $uploadfile);
wp_update_attachment_metadata( $attach_id, $attach_data );
Now your code will work. This code is tested and its working fine.
I found the function to create it!! It will create all images automatically.
https://gist.github.com/m1r0/f22d5237ee93bcccb0d9
function crb_insert_attachment_from_url($url, $parent_post_id = null) {
if( !class_exists( 'WP_Http' ) )
include_once( ABSPATH . WPINC . '/class-http.php' );
$http = new WP_Http();
$response = $http->request( $url );
if( $response['response']['code'] != 200 ) {
return false;
}
$upload = wp_upload_bits( basename($url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name, null );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name,
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
// Create the attachment
$attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );
// Include image.php
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id;
}
and for call this function, use it.
$xxx = crb_insert_attachment_from_url('http://ronaldoguedes.com.br/img/hello_word_2.png', null);

wordpress wp_handle_upload not moving the file

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

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

Why $_FILES['uploadfiles'] not working and running blank?

I am trying to upload image through custom.php in wordpress when i print the
`$_FILES['uploadfiles'];`
its not showing any thing the same code i have used before one day in another wordpress site the code is working good over there on ec2 my current wordpress is on ec2 and have bitnami image i have checked all configuration like in php.ini file upload_tmp_dir=/opt/bitnami/php/tmp ,file_uploads=on,upload_max_filesize=40M.
i am not using any form i have just added upload field in one hook that display that field on one page.
I am using thesis theme.so any boday have any idea why this happening with this code on while one copy of same code work on another wordpress with guru theme.
Bellow is the code i am using to upload image.
<input type="file" name="uploadfiles[]" id="uploadfiles" size="35" class="uploadfiles" />
<?php
$uploadfiles = $_FILES['uploadfiles'];
print_r ($uploadfiles);
if (is_array($uploadfiles)) {
echo "1";
foreach ($uploadfiles['name'] as $key => $value) {
// look only for uploded files
if ($uploadfiles['error'][$key] == 0) {
$filetmp = $uploadfiles['tmp_name'][$key];
//clean filename and extract extension
$filename = $uploadfiles['name'][$key];
// get file info
// #fixme: wp checks the file extension....
$filetype = wp_check_filetype( basename( $filename ), null );
$filetitle = preg_replace('/\.[^.]+$/', '', basename( $filename ) );
$filename = $filetitle . '.' . $filetype['ext'];
$upload_dir = wp_upload_dir();
/**
* Check if the filename already exist in the directory and rename the
* file if necessary
*/
$i = 0;
while ( file_exists( $upload_dir['path'] .'/' . $filename ) ) {
$filename = $filetitle . '_' . $i . '.' . $filetype['ext'];
$i++;
}
$filedest = $upload_dir['path'] . '/' . $filename;
/**
* Check write permissions
*/
if ( !is_writeable( $upload_dir['path'] ) ) {
$this->msg_e('Unable to write to directory %s. Is this directory writable by the server?');
return;
}
/**
* Save temporary file to uploads dir
*/
if ( !#move_uploaded_file($filetmp, $filedest) ){
$this->msg_e("Error, the file $filetmp could not moved to : $filedest ");
continue;
}
$attachment = array(
'post_mime_type' => $filetype['type'],
'post_title' => $filetitle,
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filedest );
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filedest );
echo $attach_data;
echo $filedest;
wp_update_attachment_metadata( $attach_id, $attach_data );
//echo wp_get_attachment_url( $attach_id );
//exit();
$urlimage=wp_get_attachment_url( $attach_id );
$_SESSION["oldurl"]=$urlimage;
echo $_SESSION["oldurl"];
}
}
}
?>

Resources