media_sideload_image
Downloads an image from the specified URL and attaches it to a post.
Description
(string|WP_Error) media_sideload_image( (string) $file, (int) $post_id, (constant) $desc = null, (string) $return = 'html' );
Returns (string|WP_Error)
Populated HTML img tag on success, WP_Error object otherwise.
Parameters (4)
- 0. $file (string)
- The URL of the image to download.
- 1. $post_id (int)
- The post ID the media is to be associated with.
- 2. $desc — Optional. (constant) =>
null
- Description of the image.
- 3. $return — Optional. (string) =>
'html'
- Accepts html (image tag html) or src. (URL). Default html .
Usage
if ( !function_exists( 'media_sideload_image' ) ) { require_once ABSPATH . '/wp-admin/includes/media.php'; } // The URL of the image to download. $file = ''; // The post ID the media is to be associated with. $post_id = -1; // Optional. Description of the image. $desc = null; // Optional. Accepts 'html' (image tag html) or 'src' (URL). Default 'html'. $return = 'html'; // NOTICE! Understand what this does before running. $result = media_sideload_image($file, $post_id, $desc, $return);
Defined (1)
The function is defined in the following location(s).
- /wp-admin/includes/media.php
- function media_sideload_image( $file, $post_id, $desc = null, $return = 'html' ) {
- if ( ! empty( $file ) ) {
- // Set variables for storage, fix file filename for query strings.
- preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches );
- if ( ! $matches ) {
- }
- $file_array = array();
- $file_array['name'] = basename( $matches[0] );
- // Download file to temp location.
- $file_array['tmp_name'] = download_url( $file );
- // Iferrorstoring temporarily, return the error.
- if ( is_wp_error( $file_array['tmp_name'] ) ) {
- return $file_array['tmp_name'];
- }
- // Do the validation and storage stuff.
- $id = media_handle_sideload( $file_array, $post_id, $desc );
- // Iferrorstoring permanently, unlink.
- if ( is_wp_error( $id ) ) {
- @unlink( $file_array['tmp_name'] );
- return $id;
- }
- $src = wp_get_attachment_url( $id );
- }
- // Finally, check to make sure the file has been saved, then return the HTML.
- if ( ! empty( $src ) ) {
- if ( $return === 'src' ) {
- return $src;
- }
- $alt = isset( $desc ) ? esc_attr( $desc ) : '';
- $html = "<img src='$src' alt='$alt' />";
- return $html;
- } else {
- return new WP_Error( 'image_sideload_failed' );
- }
- }