Skip to content

Instantly share code, notes, and snippets.

@m1r0
Last active October 17, 2025 00:50
Show Gist options
  • Select an option

  • Save m1r0/f22d5237ee93bcccb0d9 to your computer and use it in GitHub Desktop.

Select an option

Save m1r0/f22d5237ee93bcccb0d9 to your computer and use it in GitHub Desktop.
WP: Insert attachment from URL
<?php
/**
* Insert an attachment from a URL address.
*
* @param string $url The URL address.
* @param int|null $parent_post_id The parent post ID (Optional).
* @return int|false The attachment ID on success. False on failure.
*/
function wp_insert_attachment_from_url( $url, $parent_post_id = null ) {
if ( ! class_exists( 'WP_Http' ) ) {
require_once ABSPATH . WPINC . '/class-http.php';
}
$http = new WP_Http();
$response = $http->request( $url );
if ( 200 !== $response['response']['code'] ) {
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';
// Generate the 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

inquota commented Dec 9, 2016

Copy link
Copy Markdown

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

@SuperSpe

SuperSpe commented May 9, 2017

Copy link
Copy Markdown

very useful and works like a charm!
thanks

@komalghai

Copy link
Copy Markdown

Thanks! working well

@henrisusanto

Copy link
Copy Markdown

supercool!

@OksanaRomaniv

Copy link
Copy Markdown

Great! Helped me a lot. Thank you!

@raquelmsmith

Copy link
Copy Markdown

Worked like a charm! Thanks for the great snippet.

@sagar123123

Copy link
Copy Markdown

can i use path which is outside from my sever.

@lowrains

Copy link
Copy Markdown

that really did the job right :) thanks

@combatwombat

Copy link
Copy Markdown

Works perfectly, thanks :)

@coder054

coder054 commented Mar 9, 2019

Copy link
Copy Markdown

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

Copy link
Copy Markdown

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

otabekgh commented Jul 8, 2019

Copy link
Copy Markdown

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;
    }
}

@loxK

loxK commented Oct 29, 2019

Copy link
Copy Markdown

I would simply use for images media_sideload_image( $file, $post_id, $desc = null, $return = 'html' )

Or this for other attachments:

function add_attachment_from_url( $file ) {
        $file_array         = array();
        $file_array['name'] = wp_basename( $file );

        // Download file to temp location.
        $file_array['tmp_name'] = download_url( $file );

        // If error storing 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, 0, null );

        return $id;
    }

@kylehi2222

Copy link
Copy Markdown

I'd be so very grateful if you could give me the snippet for uploading videos to the media attachment. I'm using a external uploader and saving the data to a form field, which saves the URL to the custom field and then executes the above function but it doesn't seem to work.

`add_action('cred_save_data', 'my_save_data_action',10,2);
function my_save_data_action($post_id, $form_data)
{
// if a specific form
if ($form_data['id']==3799810)
{
if (isset($_POST['wpcf-original-video']))
{
$file = $_POST['wpcf-original-video'];
function add_attachment_from_url( $file ) {
$file_array = array();
$file_array['name'] = wp_basename( $file );

    	// Download file to temp location.
    	$file_array['tmp_name'] = download_url( $file );

    	// If error storing 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, 0, null );

		add_post_meta($post_id, 'wpcf-attached-video-id', $id, true);

    	}
}

}
}`

@amirhp-com

amirhp-com commented Jan 16, 2021

Copy link
Copy Markdown

Hey there, I'm using following functions to set Woo-commerce featured image 👍

$product = wc_get_product( $product_id);
$image_id = media_sideload_image("$img_url_base/main.jpg", $product->get_id(), $product->get_title(), 'id');
if (!is_wp_error($image_id) && is_numeric($image_id)){
   $product->set_image_id($image_id); // add featured image of product
   $product->save();
}

@arixwap

arixwap commented Jan 29, 2021

Copy link
Copy Markdown

Thankyou!
Very useful

@eyeofthenyte

Copy link
Copy Markdown

I'm really new to this but was wondering where I should insert this snippet into? Another file or save the whole php file into a certain folder.

@khoanguyen1b

Copy link
Copy Markdown

Works perfectly, thanks bro ^^

@diogenesjup

Copy link
Copy Markdown

Very very very nice work!
Thanks bro!

@zohaib87

zohaib87 commented Feb 4, 2022

Copy link
Copy Markdown

Thanks alot!!!

@FabioMontenegro

Copy link
Copy Markdown

Genial, funcionó perfecto!!!! Gracias

@integritive

Copy link
Copy Markdown

This is killer. Thank you!

@sebastopolys

Copy link
Copy Markdown

if facing function error. you need to include these two files.

    include(ABSPATH . "wp-includes/pluggable.php");
    include_once( ABSPATH . '/wp-admin/includes/image.php' );

In addition add a slash to the class instance if you are on a namespaced class

$http = new \WP_Http();

@juanRabaa

Copy link
Copy Markdown

if facing function error. you need to include these two files.

    include(ABSPATH . "wp-includes/pluggable.php");
    include_once( ABSPATH . '/wp-admin/includes/image.php' );

In addition add a slash to the class instance if you are on a namespaced class

$http = new \WP_Http();

I've haven't work with Wordpress in quite a while, but if I'm not mistaken, if you are facing this issue its because you are running the script somewhere where the necessary wordpress functions are not being included. The solution shouldn't be to include the scripts manually, but to run it in the correct environment. Whish I could be of more help, but I'm rusty with Wordpress atm .

@7iquid

7iquid commented Oct 8, 2023

Copy link
Copy Markdown

hand down thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment