Switch language

wpseek.com
A WordPress-centric search engine for devs and theme authors




media_sideload_image [ WordPress Function ]

media_sideload_image ( $file, $post_id, $desc = null )
Parameters:
  • (string) $file The URL of the image to download
  • (int) $post_id The post ID the media is to be associated with
  • (string) $desc Optional. Description of the image
Returns:
  • (string|WP_Error) Populated HTML img tag on success
Defined at:



Download an image from the specified URL and attach it to a post.

Source


<?php
function media_sideload_image($file$post_id$desc null) {
    if ( ! empty(
$file) ) {
        
// Download file to temp location
        
$tmp download_url$file );

        
// Set variables for storage
        // fix file filename for query strings
        
preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/'$file$matches);
        
$file_array['name'] = basename($matches[0]);
        
$file_array['tmp_name'] = $tmp;

        
// If error storing temporarily, unlink
        
if ( is_wp_error$tmp ) ) {
            @
unlink($file_array['tmp_name']);
            
$file_array['tmp_name'] = '';
        }

        
// do the validation and storage stuff
        
$id media_handle_sideload$file_array$post_id$desc );
        
// If error storing 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) ) {
        
$alt = isset($desc) ? esc_attr($desc) : '';
        
$html "<img src='$src' alt='$alt' />";
        return 
$html;
    }
}
?>

Examples [ wp-snippets.com ]

Top Google Search Results

More ...

0 User Note(s)

None yet. Be the first!

Add New ...



HTML5 Powered with CSS3 / Styling, Performance & Integration, and Semantics