Reputation: 944
I want to upload multiple images using wordpress.
Here is my code which is using to single upload
if ( ! function_exists( 'wp_handle_upload' ) )
require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $_FILES['photo'];
$upload_overrides = array( 'test_form' => FALSE );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
echo "File is valid, and was successfully uploaded.\n";
var_dump( $movefile);
}
else {
echo "Possible file upload attack!\n";
}
How I can upload multiple images using wordpress?
Upvotes: 0
Views: 6368
Reputation:
Try to implement like this:
$files = $_FILES['photo'];
foreach ($files['photo'] 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]
);
wp_handle_upload($file);
}
}
Upvotes: 2
Reputation: 46
You might be able to achieve what you're trying to do easier by using the native WordPress Media Uploader.
I had a good resource bookmarked at one point but can't seem to find it. I ran into a situation a few months ago that required the same thing. This is what I ended up doing:
Loading the WordPress image scripts into the beginning of my PHP script:
require_once( ABSPATH . 'wp-admin/includes/image.php' );
Then you can call the uploader on element click using jQuery like this:
jQuery(document).ready(function($) {
// Define a variable to be used to store the frame data
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = 999; // Set this
$('#upload_button').live('click', function( event ){
element = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if (file_frame) {
// Set the post ID to what we want
file_frame.uploader.uploader.param('post_id', set_to_post_id);
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: $(this).data('uploader_title'),
button: {
text: $(this).data('uploader_button_text'),
},
multiple: true // Set to false to allow only one file to be selected
});
// When an image(s) have been selected, run a callback.
file_frame.on('select', function() {
// Do something if necessary
function_to_fire();
});
// Finally, open the modal
file_frame.open();
});
});
There is an attachment
object passed to the callback function which will contain all of the IDs and such for the attachments uploaded.
The set_to_post_id
is the id of the post/page you want to "attach" the media to. If you're not trying to attach them to a post, you shouldn't need to worry about this and some of the above code will not apply.
Upvotes: 1