I am writing a custom theme/plugin in which I need to download images programatically from certain webpages to the upload folder and then insert them as part of the post.
So, I was able to find the image url's programatically, and then I need to save them to the upload folder under wp-content, however that folder has specific WordPress folder structure inside it for the saved images.
Now my question is, is there a WordPress API or function or method that will allow me to download images from the web and save them to the uploads folder? And if so, what is it.
Otherwise, what should I do to save those images?
So far, I am doing this
$filetype = wp_check_filetype(basename($image_file_name), null ); $upload_dir = wp_upload_dir(); $attachment = array( 'guid' => $upload_dir['url'] . '/' . basename( $image_file_name ), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($image_file_name)), 'post_content' => '', 'post_status' => 'inherit' ); $attachment_id = wp_insert_attachment( $attachment, $image_file_name, $post_id ); $attachment_data = wp_generate_attachment_metadata( $attachment_id, $image_file_name ); wp_update_attachment_metadata( $attachment_id, $attachment_data ); set_post_thumbnail( $post_id, $attachment_id );
But the above code is giving me the following error
imagejpeg(http://wscdn.bbc.co.uk/worldservice/assets/images/2013/07/21/130721173402_egypts_new_foreign_minister_fahmy_304x171_reuters-150x150.jpg): failed to open stream: HTTP wrapper does not support writeable connections in C:\dev\wordpress\pterodactylus\wp-includes\class-wp-image-editor.php on line 334
And after further investigation, it looks like the error is cause by
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $image_file_name );
And after even further investigation, the documentation for
wp_insert_attachment() states that
The file MUST be on the uploads directory in regards to the
So, how do I download an image and save it to my post correctly?
Thanks a lot.