---
description: >-
  https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library
---

# wp insert attachment from url, media phần 1 (ok)

Ví dụ:

```
//===========
$image_url = 'https://cdn.pixabay.com/photo/2021/02/21/14/37/little-bird-6036530_960_720.jpg';
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = basename( $image_url );
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(
  'post_mime_type' => $wp_filetype['type'],
  'post_title' => sanitize_file_name( $filename ),
  'post_content' => '',
  '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 );
//========
```

> Chú ý:
>
> Tương tự chúng ta có thể sử dụng hàm viết gon như sau
>
> wp-content/themes/twentytwentyone/single.php
>
>

```
$image_url = 'https://cdn.pixabay.com/photo/2021/02/21/14/37/little-bird-6036530_960_720.jpg';
crb_insert_attachment_from_url($image_url,0);
```

Kết quả cũng tương tự :)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_gEfbaGMkbfVYcgYX4%2F-M_gGWJB-2ydce9A2ZYT%2FScreenshot_1.jpg?alt=media\&token=aba8769e-97f5-4145-a88c-ff3b790a94be)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_gEfbaGMkbfVYcgYX4%2F-M_gGZ_i5NACW8tBCWOl%2FScreenshot_2.jpg?alt=media\&token=381d8f6f-38b1-4940-8b94-62d847694d87)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g4c_7s9hBN2kWZlLu%2FScreenshot_1.jpg?alt=media\&token=57e09973-5cc8-4f61-a4be-86eb0c9a476e)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g4gD1ebrp4ag52MDq%2FScreenshot_2.jpg?alt=media\&token=dd6ec360-2f42-4d96-9024-47e178a8ec67)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g4k0rcJJ88HY5Fsh0%2FScreenshot_3.jpg?alt=media\&token=061eefec-906d-4549-b29f-69909ae82f5b)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g4mZHjOvhsf18gRrV%2FScreenshot_4.jpg?alt=media\&token=741c125b-7e55-4d1b-b66e-80d166ab97e2)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g4q73xEGr4KbEFiKt%2FScreenshot_5.jpg?alt=media\&token=967d2c1b-93e0-4fab-9648-62a04d188245)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g6rXftSRZlttEjkcz%2FScreenshot_6.jpg?alt=media\&token=b608cacb-5c3b-4263-b7e5-3486ea6a7a0f)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g6uMDBCZ0Ux_kYajE%2FScreenshot_7.jpg?alt=media\&token=1f2daf19-0b9f-499d-a914-c9d9f4b70bdf)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g4UK5ZQ-trjYd3DFd%2F-M_g6x6LoYfes8WsFw7E%2FScreenshot_8.jpg?alt=media\&token=8ecae3f4-a5c0-4fc4-b12e-7984edcdf4f2)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_g78gWPHKGxLE0qhwP%2FScreenshot_9.jpg?alt=media\&token=0c0acaaf-0adf-422c-9a01-bb7fafde806e)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_g7Hc7bL-xk68BMiXD%2FScreenshot_10.jpg?alt=media\&token=6eafca81-9540-4a8a-a3c7-78b57702415f)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_g9fV8ZfpbTLp3T6-X%2FScreenshot_11.jpg?alt=media\&token=bc217559-2fcf-466e-b267-cd751bc0777c)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_g9inPMgBDx-48-BrZ%2FScreenshot_12.jpg?alt=media\&token=92ceacb7-f860-476a-907e-37dac4ab2d7a)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_g9lhGr_XUd7n3LJPF%2FScreenshot_13.jpg?alt=media\&token=df4d70e4-e0c8-4cbf-b9d3-7bf62f1fbc2c)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gA4u7rXnpiROJ89or%2FScreenshot_14.jpg?alt=media\&token=8757205d-ec05-42e0-a599-bdb9417a6071)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gAAfctraR79Imgna9%2FScreenshot_15.jpg?alt=media\&token=7d692ff8-429a-4d24-aad5-e5cb56e4eb23)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gBRE8JTFXsWb0UQkI%2FScreenshot_1.jpg?alt=media\&token=53fec0a7-bc0e-408d-a024-e907a17af860)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gBWJh4HL0pZ_aSqKn%2FScreenshot_17.jpg?alt=media\&token=5c8607fd-856b-42c2-bafd-5aeb708fddf6)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gCAqBEc5v6Rf3Ueu3%2FScreenshot_18.jpg?alt=media\&token=4b0a4832-4489-4fdc-957e-4f54231878a5)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gCDhl0aLKfJ_nLuGz%2FScreenshot_19.jpg?alt=media\&token=8e83fd12-e1f2-4383-8fc5-d5c70a86748a)

Full code và kết quả

```
//===========
$image_url = 'https://cdn.pixabay.com/photo/2021/02/21/14/37/little-bird-6036530_960_720.jpg';
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = basename( $image_url );
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(
  'post_mime_type' => $wp_filetype['type'],
  'post_title' => sanitize_file_name( $filename ),
  'post_content' => '',
  '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 );
//========
```

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gDRnchd531eWhaGUD%2FScreenshot_20.jpg?alt=media\&token=78c1ac88-7adb-47f6-8a09-6e89fb464648)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gDO23_yNdSNHmX17O%2FScreenshot_21.jpg?alt=media\&token=689c947b-c8da-4369-b652-a13e1ee95803)

![](https://2370029328-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LWPtKFbhw0XehxVuoiZ%2F-M_g72fkYX360x1d8Xnn%2F-M_gDXesYI7rYlmYasOW%2FScreenshot_22.jpg?alt=media\&token=c477ab3d-f5d9-49fb-843d-5b6dc592793b)

Đọc thêm 1

I am trying to programmatically add multiple images to media library, I uploaded the images to `wp-content/uploads`, now I try to use `wp_insert_attachement`.

Here's the code, however it's not working as expected, I think metadata is not properly generated, I can see the files in media library, but without a thumbnail, also if I edit the image I get an error saying to re-upload the image.

```
$filename_array = array(
   'article1.jpg',
   'article2.jpg',
);

// The ID of the post this attachment is for.
$parent_post_id = 0;

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

foreach ($filename_array as $filename) {

    // Check the type of file. We'll use this as the 'post_mime_type'.
    $filetype = wp_check_filetype( basename( $filename ), null );

    // Prepare an array of post data for the attachment.
    $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
        'post_mime_type' => $filetype['type'],
        'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );

    // Insert the attachment.
    $attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

    // Make sure that this file is included, as   wp_generate_attachment_metadata() depends on it.
    require_once( ABSPATH . 'wp-admin/includes/image.php' );

    // Generate the metadata for the attachment, and update the database record.
    $attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

}
```

[images](https://wordpress.stackexchange.com/questions/tagged/images)[attachments](https://wordpress.stackexchange.com/questions/tagged/attachments)[media-library](https://wordpress.stackexchange.com/questions/tagged/media-library)[Share](https://wordpress.stackexchange.com/q/256830)[Improve this question](https://wordpress.stackexchange.com/posts/256830/edit)Followasked Feb 17 '17 at 11:56[![](https://www.gravatar.com/avatar/a2521504bb2329422cafcedbc06d54fc?s=32\&d=identicon\&r=PG\&f=1)](https://wordpress.stackexchange.com/users/113564/adrian)[Adrian](https://wordpress.stackexchange.com/users/113564/adrian)18311 gold badge11 silver badge55 bronze badges[Add a comment](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library)

### 3 Answers

[Active](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library?answertab=active#tab-top)[Oldest](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library?answertab=oldest#tab-top)[Votes](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library?answertab=votes#tab-top)21

```
$image_url = 'adress img';

$upload_dir = wp_upload_dir();

$image_data = file_get_contents( $image_url );

$filename = basename( $image_url );

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(
  'post_mime_type' => $wp_filetype['type'],
  'post_title' => sanitize_file_name( $filename ),
  'post_content' => '',
  '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 );
```

[Share](https://wordpress.stackexchange.com/a/256834)[Improve this answer](https://wordpress.stackexchange.com/posts/256834/edit)Follow[edited Oct 22 '18 at 21:54](https://wordpress.stackexchange.com/posts/256834/revisions)[![](https://www.gravatar.com/avatar/82e31c108b36f737162ed3b43b1213e1?s=32\&d=identicon\&r=PG)](https://wordpress.stackexchange.com/users/50739/philippe-b)[philippe\_b](https://wordpress.stackexchange.com/users/50739/philippe-b)11511 gold badge11 silver badge77 bronze badgesanswered Feb 17 '17 at 12:27[![](https://www.gravatar.com/avatar/8c0d5349ed6354195a05a8a30bd1ff2f?s=32\&d=identicon\&r=PG\&f=1)](https://wordpress.stackexchange.com/users/111011/trubine)[TrubinE](https://wordpress.stackexchange.com/users/111011/trubine)80777 silver badges1212 bronze badges

* 1where is $attach\_id coming from? – [user1889580](https://wordpress.stackexchange.com/users/190834/user1889580) [Sep 27 '17 at 14:23](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library#comment416563_256834)
* it was missing... i added it – [Omtara](https://wordpress.stackexchange.com/users/130586/omtara) [Oct 30 '17 at 16:30](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library#comment421328_256834)
* 1File downloaded but no thumbnail available, attachment url also giving 404 – [Umair Hamid](https://wordpress.stackexchange.com/users/40421/umair-hamid) [May 22 '18 at 19:51](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library#comment449353_256834)
* @UmairHamid Same here. This is because the second argument of `wp_insert_attachment` should be the file path (so `$file` in this example), not the file name. I edited the answer, waiting for approval. – [philippe\_b](https://wordpress.stackexchange.com/users/50739/philippe-b) [Oct 22 '18 at 21:24](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library#comment469122_256834)
* and how can I get the new url ? – [iKamy](https://wordpress.stackexchange.com/users/163748/ikamy) [May 3 '19 at 18:19](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library#comment495629_256834)

[Show **3** more comments](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library)4

I had issues with @TrubinE's solution where image files were not getting loaded.

Here is a complete example that worked for me: [https://gist.github.com/m1r0/f22d5237ee93bcccb0d9](https://gist.github.com/m1r0/f22d5237ee93bcccb0d9)

This is a similar idea but use the WP HTTP library to fetch the content versus file\_get\_contents(). Here is the content of the github gist solution from m1r0:

```
        if( !class_exists( 'WP_Http' ) )
        include_once( ABSPATH . WPINC . '/class-http.php' );
    $http = new WP_Http();
    $response = $http->request( $meta[ 'image_url' ] );
    if( $response['response']['code'] != 200 ) {
        return false;
    }
    $upload = wp_upload_bits( basename($meta[ 'image_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',
    );

    $attach_id = wp_insert_attachment( $post_info, $file_path, $parent_post_id );
    require_once( ABSPATH . 'wp-admin/includes/image.php' );
    $attach_data = wp_generate_attachment_metadata( $attach_id, $file_path );
    wp_update_attachment_metadata( $attach_id,  $attach_data );
    return $attach_id; code here
```

[Share](https://wordpress.stackexchange.com/a/320994)[Improve this answer](https://wordpress.stackexchange.com/posts/320994/edit)Followanswered Dec 4 '18 at 16:57[![](https://www.gravatar.com/avatar/914f57e3756ceb4b5b2d6b3095f1257f?s=32\&d=identicon\&r=PG)](https://wordpress.stackexchange.com/users/11553/lance-cleveland)[Lance Cleveland](https://wordpress.stackexchange.com/users/11553/lance-cleveland)34522 silver badges77 bronze badges[Add a comment](https://wordpress.stackexchange.com/questions/256830/programmatically-adding-images-to-media-library)3

If you use WordPress' sideload feature, you can do this more easily (and have WordPress handle all of the sanitization for you).

```
<?php
$desc = 'some description';
$file = 'http://www.example.com/image.png';
$file_array  = [ 'name' => wp_basename( $file ), '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, $desc );

// If error storing permanently, unlink.
if ( is_wp_error( $id ) ) {
    @unlink( $file_array['tmp_name'] );
    return $id;
}
```

[Share](https://wordpress.stackexchange.com/a/371360)[Improve this answer](https://wordpress.stackexchange.com/posts/371360/edit)Follow\


Đọc thêm 2

```
<?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;

}
```
