Using WordPress ‘media_handle_sideload()’ PHP function

The media_handle_sideload() WordPress PHP function handles a side-loaded file in the same way an uploaded file is handled by media_handle_upload().

Usage

media_handle_sideload( $file_array, $post_id, $desc, $post_data );

Parameters

  • $file_array (array) – Array that represents a $_FILES upload array.
  • $post_id (int, optional) – The post ID the media is associated with.
  • $desc (string, optional) – Description of the side-loaded file. Default: null
  • $post_data (array, optional) – Post data to override. Default: array()

More information

See WordPress Developer Resources: media_handle_sideload

Examples

Download and sideload an image from a URL

This example downloads an image from a URL and sideloads it into the WordPress media library.

// The URL of the image to download and sideload
$url = 'https://example.com/image.png';

// Download the image to a temporary location
$tmp = download_url($url);

// Build the $file_array with the downloaded image
$file_array = array(
    'name' => basename($url),
    'tmp_name' => $tmp
);

// Check for download errors
if (is_wp_error($tmp)) {
    @unlink($file_array['tmp_name']);
    return $tmp;
}

// Sideload the image into the media library, not attached to any post
$post_id = 0;
$id = media_handle_sideload($file_array, $post_id);

// Check for upload errors
if (is_wp_error($id)) {
    @unlink($file_array['tmp_name']);
    return $id;
}

// Get the URL of the sideloaded file
$value = wp_get_attachment_url($id);

// Now you can do something with $value (or $id)

Sideload an image and attach it to a post

This example downloads an image, sideloads it into the WordPress media library, and attaches it to a specific post.

// The URL of the image to download and sideload
$url = 'https://example.com/image.png';

// Download the image to a temporary location
$tmp = download_url($url);

// Build the $file_array with the downloaded image
$file_array = array(
    'name' => basename($url),
    'tmp_name' => $tmp
);

// Check for download errors
if (is_wp_error($tmp)) {
    @unlink($file_array['tmp_name']);
    return $tmp;
}

// Sideload the image and attach it to a specific post
$post_id = 123; // Replace with the ID of the post you want to attach the image to
$id = media_handle_sideload($file_array, $post_id);

// Check for upload errors
if (is_wp_error($id)) {
    @unlink($file_array['tmp_name']);
    return $id;
}

// Get the URL of the sideloaded file
$value = wp_get_attachment_url($id);

// Now you can do something with $value (or $id)

Sideload an image with a custom description

This example downloads an image, adds a custom description, and sideloads it into the WordPress media library.

// The URL of the image to download and sideload
$url = 'https://example.com/image.png';

// Download the image to a temporary location
$tmp = download_url