Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WP: Insert attachment from URL
<?php
/**
* Insert an attachment from an URL address.
*
* @param String $url
* @param Int $parent_post_id
* @return Int Attachment ID
*/
function crb_insert_attachment_from_url($url, $parent_post_id = null) {
if( !class_exists( 'WP_Http' ) )
include_once( ABSPATH . WPINC . '/class-http.php' );
$http = new WP_Http();
$response = $http->request( $url );
if( $response['response']['code'] != 200 ) {
return false;
}
$upload = wp_upload_bits( basename($url), null, $response['body'] );
if( !empty( $upload['error'] ) ) {
return false;
}
$file_path = $upload['file'];
$file_name = basename( $file_path );
$file_type = wp_check_filetype( $file_name, null );
$attachment_title = sanitize_file_name( pathinfo( $file_name, PATHINFO_FILENAME ) );
$wp_upload_dir = wp_upload_dir();
$post_info = array(
'guid' => $wp_upload_dir['url'] . '/' . $file_name,
'post_mime_type' => $file_type['type'],
'post_title' => $attachment_title,
'post_content' => '',
'post_status' => 'inherit',
);
// Create the attachment
$attach_id = wp_insert_attachment( $post_info, $file_path, $parent_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_path );
// Assign metadata to attachment
wp_update_attachment_metadata( $attach_id, $attach_data );
return $attach_id;
}
@inquota

This comment has been minimized.

Copy link

commented Dec 9, 2016

Needed this, nice one!! Thanks ;-).

@SuperSpe

This comment has been minimized.

Copy link

commented May 9, 2017

very useful and works like a charm!
thanks

@komalghai

This comment has been minimized.

Copy link

commented May 11, 2017

Thanks! working well

@henrisusanto

This comment has been minimized.

Copy link

commented Jun 13, 2017

supercool!

@OksanaRomaniv

This comment has been minimized.

Copy link

commented Apr 9, 2018

Great! Helped me a lot. Thank you!

@raquelmsmith

This comment has been minimized.

Copy link

commented May 20, 2018

Worked like a charm! Thanks for the great snippet.

@sagar123123

This comment has been minimized.

Copy link

commented Jun 5, 2018

can i use path which is outside from my sever.

@lowrains

This comment has been minimized.

Copy link

commented Jul 10, 2018

that really did the job right :) thanks

@combatwombat

This comment has been minimized.

Copy link

commented Nov 2, 2018

Works perfectly, thanks :)

@coder054

This comment has been minimized.

Copy link

commented Mar 9, 2019

It worked with url with format: name.jpg, name.png ...
Not worked with url format look like:
https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDzrO9gxiS8hLYHKAH2AOfTAVGGQgtSkWUafoCApCIZ1vy1zo4
Also It's only add to media library, not attach to the post

@juanRabaa

This comment has been minimized.

Copy link

commented Apr 29, 2019

The $http->request( $url ) can return a WP_Error, so the if on line 20 will throw a Fatal Error when trying to use the WP_Error as an array.
Adding a is_wp_error check before could be a solution
if( is_wp_error( $response ) || $response['response']['code'] != 200 )

@otabekgh

This comment has been minimized.

Copy link

commented Jul 8, 2019

It worked with url with format: name.jpg, name.png ...
Not worked with url format look like:
https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDzrO9gxiS8hLYHKAH2AOfTAVGGQgtSkWUafoCApCIZ1vy1zo4
Also It's only add to media library, not attach to the post

public function download_attachment($post_id, $attachment_url)
{
if (filter_var($attachment_url, FILTER_VALIDATE_URL) !== FALSE) {

        $upload_dir = wp_upload_dir();
        $image_data = file_get_contents($attachment_url);
        $filename = $post_id . '_' . rand(10000, 99999) . '.jpg';
        if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'] . '/' . $filename;
        } else {
            $file = $upload_dir['basedir'] . '/' . $filename;
        }
        file_put_contents($file, $image_data);
        $wp_filetype = wp_check_filetype($filename, null);
        $attachment = array(
            'guid' => $upload_dir['url'] . '/' . $filename,
            'post_mime_type' => $wp_filetype['type'],
            'post_title' => sanitize_file_name($filename),
            'post_content' => '',
            'post_type' => 'listing_type',
            'post_status' => 'inherit',
        );
        $attach_id = wp_insert_attachment($attachment, $file);
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        $attach_data = wp_generate_attachment_metadata($attach_id, $file);
        wp_update_attachment_metadata($attach_id, $attach_data);
        return $attach_id;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.