How to Add a Featured Image from a URL in WordPress
Sometimes you need to dynamically add a featured image to a post or a custom post type from another server than the one your WordPress install is running. And you’re facing a common issue: how to do it?
Of course in this case, you need to grab the featured image from the second server, download it to your own server, in the upload folder, and assign it to the correct post. In the first step we are going to create a new post dynamically, and then we’ll deal with the featured image.
Step 1: Create a Post Dynamically
To dynamically create a post, you need to use the wp_insert_post() function. You can place the code below in an “IF” statement, otherwise each time a page is loaded it will create a new post. Not that handy.
// Register Post Data
$post = array();
$post['post_status'] = 'publish';
$post['post_type'] = 'post'; // can be a CPT too
$post['post_title'] = 'My New Post';
$post['post_content'] = 'My new post content';
$post['post_author'] = 1;
// Create Post
$post_id = wp_insert_post( $post );
Running this code will simply create a new post. Now it’s time to add the featured image.
Step 2: Add the Featured Image
To add the featured image from a URL, we have to use some WordPress functions:
- wp_upload_dir() : to retrieve the uploader folder path
- wp_mkdir_p() : to create folder and set permissions
- wp_check_filetype() : to check attachment format
- sanitize_file_name() : to format attachment file name
- wp_insert_attachment() : to create attachment
- wp_generate_attachment_metadata() : to generate attachment metadata
- wp_update_attachment_metadata() : to update attachment metadata
- set_post_thumbnail() : to assign attachment as post featured image
And now here is the code. I commented each action so that you can see exactly what’s happening when this script is running.
// Add Featured Image to Post
$image_url = 'http://s.wordpress.org/style/images/wp-header-logo.png'; // Define the image URL here
$image_name = 'wp-header-logo.png';
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); // Generate unique name
$filename = basename( $unique_file_name ); // Create image file name
// Check folder permission and define file location
if( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents( $file, $image_data );
// Check image file type
$wp_filetype = wp_check_filetype( $filename, null );
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
// Create the attachment
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
// Include image.php
require_once(ABSPATH . 'wp-admin/includes/image.php');
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
// And finally assign featured image to post
set_post_thumbnail( $post_id, $attach_id );
What’s interesting in this code is that you can place it in a loop. For example to import posts from a CSV file, or an XML file. This is really powerful and really useful, but don’t forget one thing: never ever use this script in your functions.php file without placing a conditional tag before otherwise you’ll get hundreds of new posts created in a matter of minutes!
You found this snippet useful? Please leave a comment and tell us what you created from this snippet!
This is a great guide. I’d love to hear an example of how you’ve used this in the past 😉
for some reason…the image attached is always broken… i can never see the image except ..see only the broken icon with name of the file next to it. how do i fix it
Simply Great.
Thank you, very much!
Thank you for your code and explanation. It’s useful for me and I’ll use it on my current project: I have to import a large number of posts into wordpress from typo 3 platform by means of an xml file (rss format). I have worked with rss feeds (show the rss items from other websites on my website pages). I’ll use now the rss feeds in order to insert these rss items as posts in my wordpress database.
Hi Remi
Man… You SAVE MY LIFE… your script have worked for me!!!
Thanks a million
One question:
How can I change/update the description/caption/alternative text of every image?
Hello,
First nice post. Thanks !
I want to insert a featured image but I dont want to upload this image, just to asign an url (my image is present in my library). How do I do ?
Thanks.
You’ll only be able to do it via editing your theme code. Unless there is a 3rd party plugin that you can use, which I personally am not aware of. Have a look at WordPress.org.
Hey. I use a plugin called FIFU Featured Image from URL and it works like a charm. I keep all my featured images in a protected folder on my web server and I just need the URL to add it to any of my sites. This keeps the WordPress size very small and easy to backup.
Is it possible copy multiple files at once, I have custom field with multiple url and need add all those linked images url to wp media library. Your script allow add only one image url as a featured image:
Thanks, great script! Casp
There is only 1 Featured image…That’s basically the definition of a featured image. If you need multiple images attached to the post the best way is via meta options, for example how this plugin works – http://wordpress.org/plugins/easy-image-gallery/
And so try media_sideload_image?
http://wordpress.stackexchange.com/a/46365
It is better solution, by me.
You are awesome.
I still don’t understand why we can’t use a URL as a featured image?
It’s for security reasons also to prevent people from hot-linking to other sites and stealing bandwidth.
AJ Clarke, you have a valid statement “to prevent people from hot-linking to other sites and stealing bandwidth.” However, when the “other site” is our own S3 bucket with Cloudfront enabled, this is a much better solution than using a hosting providers slow slow delivery of featured images that we are required to store on the site. Currently our site’s front page is taking 52sec to load (!?) and it’s all because of featured images (which are the only images on our site not hosted by S3… [rolling my eyes in disbelief at the ridiculousness of this scenario…]). Our hosting provider WPEngine does not allow caching plugins either.
I have no idea what to do with the code above. Is there anyway to package it into a plugin, and will it work as it is written as a plugin? I already have a WooCommerce S3 plugin which allows me to link all media to our site through easy authenticated links.
The solution I’m looking for on each of my posts is something simple like:
[featured_image][s3 link][/featured_image]
That sounds a bit crazy (52 secs) on WPEngine. I’ve never seen a site slower then 6sec load on this host. Are you positive the issues are actually with the images? Also have you made sure you aren’t loading massive images (more then 1mb each)?
I do realize that Amazon S3 is really cheap (I have them as well for hosting download files) but WPEngine also has a CDN service built-in, have you tried it instead? It would definitely make things extremely easy because all you need to do is check 1 box and everything is setup for you. Also the WPEngine caching is way better then using a plugin, so don’t stress about that 😉
Regarding the code above…this is an advanced tutorial for developers, it definitely doesn’t sound like something that would fit your needs. Sorry ;(
I found this Featured Image From URL plugin i think it allow us using url for featured image post
Yes, you can use this code to automatically set a featured image given a URL. This is to be used in your theme or plugin, it doesn’t add a field to enter a URL though.
Was searching for one hour…thanks for share
You are awesome.
Thank you.
Great code, helped me a lot! Thank you!!
Although wp_generate_attachment_metadata() does not generate my custom image file sizes set in functions.php. Any idea how this can be achieved?
For security reasons the image cropping functions in WordPress will not crop an external url and then save it to your site. You’ll need to use a 3rd party resizing script like TimbThumb for this (creates a temp folder with cropped images).
Plus, if you are using an external url and want to crop it and save it to your site anyway, you should just upload it to your media library to start with.
Thanks you so much. its what thati want love it
Hi there, what an awesome useful piece of code! I have ultimate csv import pro importing posts from a csv weekly, but I need to assign a featured image… Is it possible to use step 2 to upload the images and assign the featured image via a unique custom field value that matches the image name?
I have a string that places the image on a post from a URL using a custom field as the file name, works perfect. Just trying to get the featured image
You can set a featured image using the function set_post_thumbnail
Great, thanks a lot
Thanks for this tutorial. You’re genious 🙂
Thanks you so much.
Thank you! Very useful article!
I am trying to use this code.
The $image_url is for an image already on the local server in the /wp-content/uploads/. But not in the media library. I uploaded images via ftp. I am reusing the same set of images.
I keep getting this error.
Fatal error: Call to a member function using_permalinks() on a non-object in /home/my_user/my_url.com/wp-includes/link-template.php on line 401
Result is: image is inserted blank in the media library with no file extension. No image is set to featured image.
Thanks in advance for your help.
hi…if any possible for insert external image url to wordpress post featured image without saving image file into our upload folder.
Thanks, really helped!
I was able to get this working. It actually didn’t have anything to do with this code. It was how I declared another function earlier in my code.
This code works perfectly.
Thanks
Great!
Really great post. I was searching over 2 hours for some good snippet to insert new post and featured image from external site (actually from JSON API from external site). Didn’t test it yet, but it look perfect to me, so i am going to implement it in my new project. Thank you for sharing
Two years after the post and the code still works like a champ. Second link I looked at. First one told me to buy a plugin that did not have anything to do with what I needed.
Thank you for this great detailed post. Once I integrated the code with my create post loop. It worked the first try. Only had to replace the static url with my $url variable done.
Thank You!!!!
Great post, however the code doesn’t take into consideration files that have the same name. We need to check the directory and increment the file name value if already exists.
$upload_dir = wp_upload_dir(); // Set upload folder
$image_data = file_get_contents($image_url); // Get image data
$newfilename = wp_unique_filename( $upload_dir[‘path’], $NAME_OF_IMAGEFILE_WITH_EXTENSION );
$filename = basename($newfilename); // Create image file name
one extra line of code did the trick for me to set the filename to something unique.
You are correct! Awesome, thank you for sharing I have updated the code on the post.
still useful, thx! 🙂
thanks for this code <3 … but one question.. what if I want to get url of featured image after it assigned to the post ?
Great, I am glad you found it useful. If you want to get the featured image URL, you can use the WordPress function wp_get_attachment_url() which will return the URL of any image defined in the the media library.
I have been looking for this piece of a code for days now, Thanks a mill Remi!!
Thank you very much for this code
Awesome – easy to understand and easy to implement. Thanks Remi, I am also looking to upload the image then set it to the feature image. Have you written about that? Let me know please.
Setting the image as the featured image is mentioned in the code via the set_post_thumbnail() function which is the last line of the second snippet. Please have another look.
I’d like to say thank you. This is great guide.
tnx a lot
works like a charm
Thank you! Works with latest WP 4.7.2
I will use this to include thumbnails when auto-importing albums as woocommerce product.
You just saved my day with a quick, clean and well documented code. You deserve a winning cup. 🏆
Worked perfectly on WP 4.8.2 10/28/17.. Awesome! Thank you so much.
Hi
This is prabhu. i’m a web developer and i work with WordPress. you article about how to add features image from a URL in WordPress is a useful information. its really a worth one. Thanku so much.
Broken image are uploading.
To be honest, I personally don’t really recommend uploading a featured image by using a URL. But if you are trying to use images from someone else’s site and the are broken on the front-end of your site, it’s possible that person is blocking hotlinking. It’s not an issue – they’re just protecting their content (and server resources).
However, if you’re having trouble uploading images on your own website it could be a simple upload error. If it’s a new issue, check to see if a recently installed plugin is to blame, Just deactivate any newly installed plugins to see if it fixes the issue. If not, check to see if you need to increase your PHP memory limit (or possibly even upgrade your server’s version of PHP – your host should be able to help with this one). Or if you’re uploading an uncommon file type, you might need to edit the wp-config file for your site to allow the new file type (such as to add .svg images).
Hopefully one of those tips will help!
This is indeed a great code snippet, I created a drop shipping plugin using this snippet to add product image from url. Thanks
Awesome !! Thanks A LOT !!
THANK YOU! This has helped me a lot.
thank you very much. awesome!