Currently set to No Index
Currently set to No Follow

Get the Official WPSaviour App Now!


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        = ''; // 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!

Download The WPSaviour App Now

Related posts
Beginner’s GuideBlogTips

Top 5 free payment gateway plugins for WordPress in India (2020)

Beginner’s GuideBlogTips

Best WooCommerce International Payment Gateways for WordPress in 2020

Best WordPress PluginsBlog

WordPress 5.4 Will Add Lazy-Loading to All Images

Beginner’s GuideBlog

How to Add a Preloader Animation to WordPress (Step by Step)

Sign up for our Newsletter and
stay informed