My basic scenario is the following:
I have a directory on my server that gets filled with images via ftp every once in a while. I would want to move these images to the wp upload directory and then add them to the media library with wp_insert_attachment()
. I thought wp_handle_sideload()
to be the correct function for this but if fed with an absolute path to one of the images it returns an error.
Heres my code so far:
function oo_attach_images($images, $id){
//$images is an array of anbsolute image paths, $id is the id of a post I want the images to be attached to.
require_once(ABSPATH . '/wp-admin/includes/file.php');
require_once(ABSPATH . '/wp-admin/includes/image.php');
foreach($images as $image){
$override = array('test_form' => FALSE);
$file = wp_handle_sideload($image, $override);
print_r($file); //returns: Array ( [error] => )
$attachment = array(
'post_mime_type' => $file['type'],
'post_title' => basename($image),
'post_content' => ' ',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file['file'], $id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file['file'] );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
I looked into similar questions, but none of the solutions outlined there seemed to have anything to do with the sideload itself failing.
Frankly, I believe that I do not pass the right kind of file path to wp_handle_sideload()
, but since its undocumented in codex I have no idea what kind of input it might expect. Does anyone know what I need to change to make this work?
Your files array needs to mimic the $_FILES global so you need to make a dummy page with some file inputs that prints or dumps the contents of $_FILES to see how it is structured. Make a variable that looks like that with your data and pass that
wp_handle_sideload()
.EDIT:
This answer was correct at the time of writing and is if you wish to use
wp_handle_sideload()
.media_handle_sideload()
allow you to attach the media to a post at the same time.See @anatol’s own answer for a full solution.
This is the surprisingly simple code that ultimately worked out to do what it’s supposed to:
I used Anatol’s code but ran into trouble when pulling images using HTTP. To fix this, use download_url first to get a local copy of the image.
It’s also useful to know that media_handle_sideload returns the attachment_id number which you can use to display the image after you’ve uploaded it.
try