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:devwordpresspterodactyluswp-includesclass-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 $image_file_name
So, how do I download an image and save it to my post correctly?
Thanks a lot.
I recently had to do this via a nightly cron script for a social media stream. $parent_id is the ID of the post you want to attach the image to.
ex:
You have no posted the code used to fetch and save the image, so is impossible to say where is the error.
Try this code for grab and save the image:
Then simply use these functions in combination with your code, like so:
Remember also that you must to include wp-admin/includes/image.php in your code for the function
wp_generate_attachment_metadata()
to work, see the CodexHope this help, but please note that all the code here is not tested.
You can use this function to remote upload an image to uploads folder and set it as featured image.
Usage:
Just use default wp (v2.6.0+) function: