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?
media_handle_sideload()
. The problem was, that these wp upload functions expect an array with the same structure as$_FILES
passed, therefore I passed my absolute paths and other info into the function as an array similar to$_FILES
. Id love to give yout the code, but thanks to the "you cant answer your own question yet" limitation ill have to wait some more before ill be able to.