Skip to main content
WordPress made easy with the drag & drop Total WordPress Theme!Learn More

How to Add a Featured Image from a URL in WordPress

Last updated on:

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:

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!

wordpress-featured-image-url
Article by Remi WPExplorer.com guest author
Subscribe to the Newsletter

Get our latest news, tutorials, guides, tips & deals delivered to your inbox.

58 Comments

  1. AJ Clarke | WPExplorer

    This is a great guide. I’d love to hear an example of how you’ve used this in the past 😉

    • littledevil2014

      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

  2. Fco. Javier Prada

    Simply Great.

    Thank you, very much!

  3. thenetbreeze

    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.

  4. juan

    Hi Remi
    Man… You SAVE MY LIFE… your script have worked for me!!!
    Thanks a million

  5. juan

    One question:
    How can I change/update the description/caption/alternative text of every image?

  6. easycondor

    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.

    • AJ Clarke | WPExplorer

      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.

    • Mike Simpson

      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.

  7. CasperTi

    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

    • AJ Clarke | WPExplorer

      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/

  8. Honza Gál

    And so try media_sideload_image?
    http://wordpress.stackexchange.com/a/46365
    It is better solution, by me.

    • Zaheer Abbas

      You are awesome.

  9. iamnormal0

    I still don’t understand why we can’t use a URL as a featured image?

    • AJ Clarke

      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]

        • AJ Clarke

          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 ;(

      • Warung

        I found this Featured Image From URL plugin i think it allow us using url for featured image post

        • AJ Clarke

          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.

  10. anthony

    Was searching for one hour…thanks for share

  11. Shahbaz Badar

    You are awesome.

    Thank you.

  12. Ben

    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?

    • AJ Clarke

      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.

  13. Manoj Sharma

    Thanks you so much. its what thati want love it

  14. Aaron

    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

  15. suneth

    Great, thanks a lot

  16. suascat

    Thanks for this tutorial. You’re genious 🙂

  17. Suraj

    Thanks you so much.

  18. Alexey Vertinsky

    Thank you! Very useful article!

  19. Kevin Brent

    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.

  20. jegadeesh

    hi…if any possible for insert external image url to wordpress post featured image without saving image file into our upload folder.

  21. Michael

    Thanks, really helped!

  22. Kevin Brent

    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

  23. Abid Nevesinjac

    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

  24. Marty

    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!!!!

  25. Jay

    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.

    • AJ Clarke

      You are correct! Awesome, thank you for sharing I have updated the code on the post.

  26. Sahin

    still useful, thx! 🙂

  27. nadera

    thanks for this code <3 … but one question.. what if I want to get url of featured image after it assigned to the post ?

    • AJ Clarke

      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.

  28. teddyatpixventive

    I have been looking for this piece of a code for days now, Thanks a mill Remi!!

  29. rvghoghari

    Thank you very much for this code

  30. Ahmad Sayeed

    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.

    • AJ Clarke

      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.

  31. NGUYEN NGOC PHU

    I’d like to say thank you. This is great guide.

  32. milad

    tnx a lot
    works like a charm

  33. Erik

    Thank you! Works with latest WP 4.7.2
    I will use this to include thumbnails when auto-importing albums as woocommerce product.

  34. Cédric de Mondenard

    You just saved my day with a quick, clean and well documented code. You deserve a winning cup. 🏆

  35. Dave

    Worked perfectly on WP 4.8.2 10/28/17.. Awesome! Thank you so much.

  36. Prabhu

    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.

  37. Zaheer Abbas

    Broken image are uploading.

    • Kyla

      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!

  38. Irfan Razzaq

    This is indeed a great code snippet, I created a drop shipping plugin using this snippet to add product image from url. Thanks

  39. AlmasSub

    Awesome !! Thanks A LOT !!

  40. Marian

    THANK YOU! This has helped me a lot.

  41. reza altafi

    thank you very much. awesome!

Leave a Reply

Your email address will not be published. Required fields are marked *

Learn how your comment data is processed by viewing our privacy policy here.