Programmatically Add Images to WordPress Posts Using an External URL

by | April 5, 2023 | PHP, Website Development

This page may contain affiliate links to recommended products or services. If you choose to purchase after clicking a link, I may receive a commission at no additional cost to you.

Last updated on: April 7, 2023

In this article, I will show you how to programmatically add images to a WordPress post using the absolute URL for an image file hosted externally from your website. Why would you want to do this? Well, maybe you want to use an image on another server or website as your post’s featured image. Or perhaps, you have a comma-separated list of image URLs in a spreadsheet from customer-entered form data — and rather than manually add each image to a post you’d prefer to automate the workflow to save time. Regardless, we will get that image and attach it as a featured image to our WordPress post.

Overview

No matter what image you’re working with, the process to grab an image from somewhere else and put it on your WordPress website is essentially the same. You have to download the image from the external location, upload it to your website, turn it into a WordPress media attachment, and assign it to a specific post.

  • Download the image from an external URL
  • Upload the image to your WordPress website
  • Turn the image into a media attachment
  • Assign it to a specific post

Start with a WordPress Post ID

If you already know which WordPress post you want to attach the image to that’s great. However, it’s likely if you’re using this technique to programmatically attach an image to a post that you’re also dynamically creating posts on the fly.

Imagine you’re inserting a post using wp_insert_post() like so:

$post = array(
      'post_title' => $post_title,
      'post_content' => $post_content,
      'post_status' => 'publish'
);

// Create the post and save the id.
$post_id = wp_insert_post($post);

Creating a post like this returns a post ID you can use to attach the image.

Attaching an Image to a Post ID

Next step, getting the image and attaching it to the post ID.

Define the Image Parameters

Your initial step is simply to set up the image for processing.

/*
* Add Featured Image to Post
*/
// An absolute URL to an image that lives on an external server.
$image_url = 'https://cdn.pixabay.com/photo/2017/11/26/15/16/smiley-2979107_960_720.jpg';

// Get the image's file name (e.g. your-image.jpg).
$image_filename = basename( $image_url );

// Specificy your WordPress upload folder.
$upload_dir = wp_upload_dir();

// Image's filename with its extension.
$image_data = file_get_contents($image_url); // Get image data.

// Generate unique name
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_filename );

// Create the image file name for WordPress.
$filename = basename( $unique_file_name );

Define the Image’s Upload Location

Next, check permissions on the upload folder and define the final destination for the image file.

// Check upload folder permission and set the image file's location.
if( wp_mkdir_p( $upload_dir['path'] ) ) {
  $file = $upload_dir['path'] . '/' . $filename;
} else {
  $file = $upload_dir['basedir'] . '/' . $filename;
}

wp_mkdir_p() recursively creates a directory based on a full path. The new path is where the image will go. If that doesn’t work then define the image’s destination as the root of your WordPress upload folder.

Save the Image

Next, save the image to the destination by creating the image file on your own server where your WordPress site is.

// Create the image file on your WordPress server.
file_put_contents( $file, $image_data );

At this point, the image is on your web server. You can access and view it on your website, but it’s not yet woven into WordPress as an attachment file such as if you had manually uploaded it through the WordPress Media Manager.

Make the Image a Media Attachment

The next step is linking the image as a WordPress media attachment.

// Retrieve the image's file type.
$wp_filetype = wp_check_filetype( $filename, null );

// Set the image's media attachment data.
$attachment_args = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => 'Content for the media attachment page (optional).',
    'post_status'    => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment_args, $file, $post_id );

wp_check_filetype() gets the image’s file type from the image’s file name, so you can use it to set the attachment’s mime type. The rest of this code should be self-explanatory.

  • post_title is the attachment’s post tile.
  • post_content is the content that will display on the single template of the attachment’s page. Not all WordPress themes utilize this template, so it’s usually OK to leave the value blank.
  • post_status sets the published status of the attachment. Media attachment files are typically child items and closely tied to the post they’re attached to, so setting this value to inherit allows the post_status to mimic the post_status of the post it is assigned to.

wp_insert_attachment() does the work of creating an official WordPress Media Attachment from the image.

  • $attachment_args describe the arguments you’ve set to define the image attachment.
  • $file is the reference to the image file you created.
  • $post_id is the ID of the WordPress post you want to attach the image to.

Create WordPress Attachment Metadata

Next up, you need to create the attachment metadata for your image and generate the sub-sizes of your images.

// Include WordPress' image.php file to use its PHP functions.
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 );

wp_generate_attachment_metadata() generates attachment metadata and creates image sub-sizes for images. And subsequently, wp_update_attachment_metadata() updates the metadata for an attachment. Together, they create the metadata for the image’s alternate sizes and link it to the image attachment.

Set the Post’s Featured Image

The last and final step of programmatically attaching an image from an external URL to a WordPress post as its featured image is attaching it to the post as the featured image.

// Assign the attachment as the post's featured image.
set_post_thumbnail( $post_id, $attach_id );

And, that’s it. You’ve done it.

Full Code Example

Altogether, here’s the full code from the example. If you’re going to use it then remember to customize it with your own image’s URL and post content, etc.

/*
* Dynamically create a post to attach an image to.
*/
$post = array(
      'post_title' => $post_title,
      'post_content' => $post_content,
      'post_status' => 'publish'
);

// Create the post and save the id.
$post_id = wp_insert_post($post);

/*
* Add Featured Image to Post
*/
// An absolute URL to an image that lives on an external server.
$image_url = 'https://cdn.pixabay.com/photo/2017/11/26/15/16/smiley-2979107_960_720.jpg';

// Get the image's file name (e.g. your-image.jpg).
$image_filename = basename( $image_url );

// Specificy your WordPress upload folder.
$upload_dir = wp_upload_dir();

// Image's filename with its extension.
$image_data = file_get_contents($image_url); // Get image data.

// Generate unique name
$unique_file_name = wp_unique_filename( $upload_dir['path'], $image_filename );

// Create the image file name for WordPress.
$filename = basename( $unique_file_name );

// Check upload folder permission and set the image file's location.
if( wp_mkdir_p( $upload_dir['path'] ) ) {
  $file = $upload_dir['path'] . '/' . $filename;
} else {
  $file = $upload_dir['basedir'] . '/' . $filename;
}

// Create the image file on your WordPress server.
file_put_contents( $file, $image_data );

// Retrieve the image's file type.
$wp_filetype = wp_check_filetype( $filename, null );

// Set the image's media attachment data.
$attachment_args = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => sanitize_file_name( $filename ),
    'post_content'   => 'Content for the media attachment page (optional).',
    'post_status'    => 'inherit'
);

// Create the attachment
$attach_id = wp_insert_attachment( $attachment_args, $file, $post_id );

// Include WordPress' image.php file to use its PHP functions.
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 );

// Include WordPress' image.php file to use its PHP functions.
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 );

// Assign the attachment as the post's featured image.
set_post_thumbnail( $post_id, $attach_id );

Alternative Method

In case you don’t need to set all the attachment args and metadata stuff when attaching your external image as a post’s featured thumbnail, WordPress also provides a simpler way of assigning an image via URL to a post as the featured image.

media_sideload_image() downloads an image from the specified URL, saves it as an attachment, and optionally attaches it to a post.

$url = "https://cdn.pixabay.com/photo/2014/12/28/13/20/wordpress-581849_960_720.jpg"
$post_id = 1;
$description = "The Title of Your Attachment";
$image = media_sideload_image( $url, $post_id, $description );

As with many WordPress functions, however, it’s worth looking over the user-contributed comments on this one and proceeding with caution.

For instance, the very first user comment warns:

A word of caution, the “description” that’s the third value for this function is actually the attachment’s “TITLE” and not it’s “DESCRIPTION”.

There is no support for adding the actual description with media_sideload_image.

-tgiokdi
Floyd Hartford is a website developer from southern Maine. He's focused on creating and building WordPress websites and loves spending time digging into code like HTML, CSS, scss, jQuery, PHP, and MySQL.

0 Comments

Submit a Comment

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

thirteen − seven =

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Looking for WordPress Help?

I’m a freelance web developer specializing in small business and corporate marketing websites.

Pin It on Pinterest