WordPress: Upload images to ACF using repeater image field - php

My HTML form allows users to select any number of images to be uploaded to a custom post type. I've created a repeater field in ACF called 'images', of 'image' objects.
How do I save the uploaded images into that repeater field?
This is what I currently have:
$files = $_FILES['file'];
$image_number = 1;
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]
);
$uploaded_file = wp_handle_upload($file, array('test_form' => FALSE));
update_sub_field( array('images', $image_number++, 'image'), $uploaded_file, $post_id);
}
}
But the images aren't saved. Any help appreciated, thanks!

As far as I see, your use of the update_field function especially it's signature is wrong. You mixed up the parameters. Have a look here: Wordpress ACF: How to add rows to a repeater field attached to a user via custom code (PHP)

Try the following code. It is working for me. Although it's an old post, it might help someone else in future.
$attachment = array(
'guid' => $upload_dir . '/' . basename( $filename ),
'post_mime_type' => $filetype['type']
);
$attachment_id = wp_insert_attachment($attachment, $filename, $parent_post_id);
$row = array(
'name' => "Hello",
'logo' => $attachment_id, // this is where you put post id of your image
'website' => "http://hello.com"
);
add_row( "repeater_field", $row, $blog_post_id);
I also noticed that add_row works only if you have already at least one row. But if you want to add a new row, use update_field. Take a look here: add_row in ACF Pro isn't saving repeater values

Related

Upload multiple images to woo commerce in php

I have a site that uses php to upload product information to woo commerce. everything works fine; however i am now stuck trying to work out how to add multiple images. I have got it adding 1 image fine as seen below
$imageURL = "https://www.[website].co.uk/new/wp-content/uploads/products/";
$imageURL = $imageURL . $product->ITEMNO . ".JPG";
if (!(false === file_get_contents($imageURL,0,null,0,1))) {
$data['images'] = [[
'name' => $product->DESC,
'src' => $imageURL,
'alt' => $product->DESC
]];
echo "Image URL: " . $imageURL . "\n";
}
$woocommerce->put('products/'.$searched[0]->id, $data);
If i try adding in another image using $data['image'] = ... with different data; it just overwrites the image
Im assume EITHER theres a different input for adding it to the product gallery instead of just the main product image. but i couldnt see one at https://woocommerce.github.io/woocommerce-rest-api-docs/?php#product-images-properties
OR if its to do with different id's for the image. Of which i tried adding 'id' => 56565656, to the $data['images'] but it just crashed on me.
Any help would be appreciated.
From woo commerce docs, 'images' is an array type; so it was just figuring out how to write it to get the 2nd image in the second slot of the array; find below the answer
$data['images'] =
[
[
'name' => $product->DESC,
'src' => $imageURL,
'alt' => $product->DESC
],
[
'name' => $product->DESC2,
'src' => $imageURL2,
'alt' => $product->DESC2
]
];

Problems saving title/description with cakephp2.0 file upload plug in

I am using http://milesj.me/code/cakephp/uploader#configuration to upload images. I got it to work fine (in terms of uploading images) but I can't get it to save title/description in my db.
so I have Image.php model that has the following code
<?php
class Image extends AppModel {
var $name = 'Image';
public $actsAs = array('Uploader.Attachment', 'Uploader.FileValidation');
public $validate = array(
'title' => array( 'rule' => 'notEmpty')
);
}
In my view I have bunch of fields such as
echo $this->Form->input('title');
My ImagesController.php add function looks like this
function add($number_of_images = 1){
if (!empty($this->data)) {
var_export($this->data);
exit();
$count = 1;
foreach($this->data['Images'] as $entry){
$file_name = "file" . $count;
if ($data_s = $this->Uploader->upload($file_name)) {
$this->Image->saveAll($data_s);
}
$count++;
}
$this->Session->setFlash("Your image(s) has been saved");
$this->redirect(array('action'=>'index'));
}else{
// make sure 10 is max amount of images a user can upload
if($number_of_images <= 10 ){
$this->set('number_of_images', $number_of_images);
}else{
// set to default 1
$this->set('number_of_images', '1');
}
}
}
When I click save, the image gets uploaded but title/description doesnt get uploaded or validated. This is how my var_export($this->data) looks like
array ( 'selectImages' => '1', 'Images' => array ( 'title' => 'adsafdas', 'description' => 'asdfasd', 'tags' => '', 'file1' => array ( 'name' => '308462_926071922398_11704522_41424436_637322498_n.jpg', 'type' => 'image/jpeg', 'tmp_name' => '/tmp/php7tycbu', 'error' => 0, 'size' => 81638, ), ), )
How can I fix this?
According with the link, $this->Uploader->upload() returns only data of file uploaded. So, you need merge this array with the other fields of your form $this->data before saveAll.
However, if you need validate form data before upload the file, use $this->Image->validates($this->request->data).

Custom field in Drupal 7 with multiple file fields

I'm making a custom "video" field that is supposed to accept several files (for different video formats) and a caption. So far the schema is fine, but I can't get it to upload and store the actual files.
My code in hook_field_widget_form looks like this (only pasting relevant bits):
$element['mp4'] = array(
'#type' => 'file',
'#title' => 'MP4 file',
'#delta' => $delta,
);
$element['ogg'] = ... /* similar to the mp4 one */
$element['caption'] = array(
'#type' => 'textfield',
'#title' => 'Caption',
'#delta' => $delta,
);
Also, in my .install file:
function customvideofield_field_schema($field) {
return array(
'columns' => array(
'mp4' => array(
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'default' => 0,
),
'ogg' => ... /* similar to mp4 */
'caption' => array(
'type' => 'varchar',
'length' => 255,
),
)
);
}
And the error I'm getting is when I try to store data. I get the form ok, and the database looks fine (the fields Drupal generates at least), but when it tries to do an INSERT, it fails because the value it tries to get into those integer fields is an empty string.
From what I understand, they have to be integers, right? (fids?) But I'm guessing the files are not being uploaded, even though I do get the right interface for uploading files.
Drupal shows you the INSERT query it tries to do, which is too long to post here, but I can see there that the value for the caption field (which is just a text field), is fine in the query, so it's only a problem with the file fields.
You probably want to use the managed_file field type instead, it handles uploading the file and registering it in the managed_files table for you. Then you would just add a submit function to your widget form and put the following code (from the FAPI page linked to above):
// Load the file via file.fid.
$file = file_load($form_state['values']['mp4']);
// Change status to permanent.
$file->status = FILE_STATUS_PERMANENT;
// Save.
file_save($file);
// Record that the module (in this example, user module) is using the file.
file_usage_add($file, 'customvideofield', 'customvideofield', $file->fid);
Hope that helps
EDIT
The core file module handles the actual submission for this using hook_field_presave(), my best guess is that this code would work:
function customvideofield_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
// Make sure that each file which will be saved with this object has a
// permanent status, so that it will not be removed when temporary files are
// cleaned up.
foreach ($items as $item) {
$file = file_load($item['mp4']);
if (!$file->status) {
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
}
}
}
That assumes the file ID column for your field is the one called mp4.
Remember to clear Drupal's caches when you implement the new hook or it won't be registered.
I haven't tried file uploading in my Drupal modules yet, but can you check does your form tag have the attribute enctype
="multipart/form-data"?
I would expect Drupal ought to include this automatically, but without it the file fields won't work, which seems to be what you're experiencing.
James

How To Specify Filename When Uploading Product Picture Using The Magento Soap Api

I'm using the Magento Soap Api to upload pictures of products. I can't seem to specify the name I wish Magento so save the file as on the server even though I specify the "name" as per the Magento documentation.
I'm using Magento 1.2.1.2 and can't upgrade as the site uses modules that break in newer version.
Any thoughts on how I can specify the file name that Magento saves the image as?
The code I'm using:
$client->call(
$session_id,
'catalog_product_attribute_media.create',
array(
$sku,
array(
'file' => array(
'content' => base64_encode(file_get_contents($filename)),
'mime' => $imageinfo['mime'],
'name' => $filename
),
'label' => $description,
'types' => array(
'image',
'small_image',
'thumbnail'
),
'exclude' => FALSE
)
)
);
You can't specify the filename. The only solution would be for you change the Magento files to allow a filename as suggested in this thread. For your convenience I've included the solution below (and adapted it based on the fact that you're sending the filename as name above):
Modify ./app/code/core/Mage/Catalog/Model/Product/Attribute/Media/Api.php:
You'll want to replace $fileName = 'image.' . $this->_mimeTypes[$data['file']['mime']]; with:
if ( ! empty($data['file']['name']) )
$fileName = $data['file']['name'];
else
$fileName = 'image.' . $this->_mimeTypes[$data['file']['mime']];
If you feel a little more adventurous, you could extend the class instead of changing it and override the create function with your own functionality.

Zend File Validator return wrong message

below code return "File '' is not readable or does not exist" always:
$filters = array(
'*' => 'stringTrim'
);
$validators = array(
'image'=> array(
'allowEmpty' => TRUE,
new Zend_Validate_File_ImageSize(array('minheight'=>0,'minwidth'=>0,'maxheight'=>1024,'maxwidth'=>1024)),
)
);
$input = new Zend_Filter_Input($filters, $validators);
$input->setData(array_merge($data, $_FILES));
if (!$input->isValid()) {
$this->_errors = $input->getMessages();
}
The input name of your file input has to be image. Also, be sure your form has enctype="multipart/form-data". The format of $_FILES is explained here.
Aside from that I don't detect any code in Zend_Validate_File_ImageSize that can operate on $_FILES. I think you've got to pass the actual path to the file, e.g. 'image' => $_FILES['image']['tmp_name'] (in your $input->setData() call).

Categories