Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WordPress] Add file to media library programmatically
<?php
$file = '/path/to/file.png';
$filename = basename($file);
$upload_file = wp_upload_bits($filename, null, file_get_contents($file));
if (!$upload_file['error']) {
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => $parent_post_id,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
@paperrobots

This comment has been minimized.

Copy link

@paperrobots paperrobots commented Aug 16, 2014

Great script. I'm trying to insert an alt tag as well right away. How do you recommend accomplishing that?

@tallesairan

This comment has been minimized.

Copy link

@tallesairan tallesairan commented Nov 11, 2015

great codee

@fastesol

This comment has been minimized.

Copy link

@fastesol fastesol commented Feb 7, 2016

Not working.

Fatal error: Call to undefined function wp_get_current_user() in /home/username/public_html/wp/wp-includes/capabilities.php on line 424

@Serjilio

This comment has been minimized.

Copy link

@Serjilio Serjilio commented Mar 14, 2016

Perfect! Thank you!

@aliaksandrI

This comment has been minimized.

Copy link

@aliaksandrI aliaksandrI commented Apr 2, 2016

Just registred to say thank you - this is indeed working great with latest Wordpress! You're the best, hissy!

@PoMkaNik

This comment has been minimized.

Copy link

@PoMkaNik PoMkaNik commented Apr 17, 2016

Great code! Working perfect!

@oprog

This comment has been minimized.

Copy link

@oprog oprog commented May 15, 2016

Just used with WP 4.5.2 for a custom migration script and it works fine.

@megitra

This comment has been minimized.

Copy link

@megitra megitra commented Sep 9, 2016

how do I fill the $parent_post_id variable? if I put this code in function.php, and I will upload image like using the uploader in wp-admin/media-new.php

@riyo007

This comment has been minimized.

Copy link

@riyo007 riyo007 commented Sep 27, 2016

Great one, works perfect, Thanks a lot :)

@xvilo

This comment has been minimized.

Copy link

@xvilo xvilo commented Oct 14, 2016

Ty Mate, I have been looking for ages to get stuff working properly. Now it does!

@everaldomatias

This comment has been minimized.

Copy link

@everaldomatias everaldomatias commented Oct 31, 2016

Perfect.
Congratulations.

@athijazi

This comment has been minimized.

Copy link

@athijazi athijazi commented Nov 1, 2016

Nice man. it helps too much.

@rathinavital

This comment has been minimized.

Copy link

@rathinavital rathinavital commented Nov 30, 2016

It's perfect....

@rvgud1

This comment has been minimized.

Copy link

@rvgud1 rvgud1 commented Dec 15, 2016

thank you very much

@DavidV-RSA

This comment has been minimized.

Copy link

@DavidV-RSA DavidV-RSA commented Dec 19, 2016

works great!

@grex22

This comment has been minimized.

Copy link

@grex22 grex22 commented Dec 19, 2016

This is fantastic! Thank you!!

@qant

This comment has been minimized.

Copy link

@qant qant commented Jan 16, 2017

This is just a code from WORDPRESS CODEX page... so lol... ppl dont like to read documentation...
https://codex.wordpress.org/Function_Reference/wp_insert_attachment

@vishalkakadiya

This comment has been minimized.

Copy link

@vishalkakadiya vishalkakadiya commented Jan 17, 2017

Great script, Thanks Man. Thank you so much.
Fantastic!

@billzhong

This comment has been minimized.

Copy link

@billzhong billzhong commented Feb 27, 2017

@qant This is NOT. The key point of this gist is using wp_upload_bits() function.

@hemant-tivlabs

This comment has been minimized.

Copy link

@hemant-tivlabs hemant-tivlabs commented Jul 6, 2017

Worked great. Thanks!

@peter279k

This comment has been minimized.

Copy link

@peter279k peter279k commented Sep 11, 2017

It worked successfully! Thank you for this sample code!

@peird

This comment has been minimized.

Copy link

@peird peird commented May 8, 2018

Thanks for the snippet! Works great.

In case anyone gets the following order:
Fatal error: Call to undefined function wp_get_current_user()

Check out following post: https://stackoverflow.com/a/6127607

@lowrains

This comment has been minimized.

Copy link

@lowrains lowrains commented Jul 10, 2018

awesome stuff

@coder618

This comment has been minimized.

Copy link

@coder618 coder618 commented Oct 26, 2018

Thanks man

@kensington133

This comment has been minimized.

Copy link

@kensington133 kensington133 commented May 29, 2019

Still works in 5.2, thanks for saving me a bunch of time! 👍

@oadekoya12

This comment has been minimized.

Copy link

@oadekoya12 oadekoya12 commented May 29, 2019

Hi guys,
I have a different case study.
I want to add a file to the media library without attaching it to any posts/pages.
That is, I do not want to use wp_insert_attachment() function.

Thanks

@kensington133

This comment has been minimized.

Copy link

@kensington133 kensington133 commented May 30, 2019

@oadekoya12 I think you can set the 'post_parent' => $parent_post_id, to null or an empty string so the media becomes "unattached".

@oadekoya12

This comment has been minimized.

Copy link

@oadekoya12 oadekoya12 commented May 30, 2019

@kensington133,
Thanks, It works.

@thegreentimtam

This comment has been minimized.

Copy link

@thegreentimtam thegreentimtam commented Aug 5, 2019

Using this code for MP3s. Works great!

Any ideas how to get the Post ID of the newly created media to add a featured image?

@hissy

This comment has been minimized.

Copy link
Owner Author

@hissy hissy commented Aug 5, 2019

@thegreentimtam $attachment_id is the newly created post id

@fredbradley

This comment has been minimized.

Copy link

@fredbradley fredbradley commented Aug 8, 2019

Hey - been using this for a while and it works great.

However I have a new requirement where I just want to import images to Media Library, but NOT set as attachment to particular post.

Is that possible? All the functions here require a $parent_post_id

@fredbradley

This comment has been minimized.

Copy link

@fredbradley fredbradley commented Aug 8, 2019

Sorry - just read the docs for wp_insert_attachment().. turns out you don't have to supply a parent id.

https://codex.wordpress.org/Function_Reference/wp_insert_attachment

@hissy

This comment has been minimized.

Copy link
Owner Author

@hissy hissy commented Aug 8, 2019

Yup, you don't have to pass $parent_post_id if you don't want to attach it

@srjwebster

This comment has been minimized.

Copy link

@srjwebster srjwebster commented Nov 27, 2019

This works consistently as long as you're not waiting for the reply. I am using a rest endpoint to generate products from a remote source and using a method link this to create the images.

I have found if you have more than a few media sizes this can easily risk timing out the web-server if it has an anywhere near reasonable wait time.

A site I'm using has 28 different media sizes and we never manage to run the wp_generate_attachment_metadata and get a reply before the timeout is reached. Annoyingly our service then assumes failure and tries again, and again and again. Eventually crashing the server and leaving us with hundreds of duplicate images!

Just recording this here as its top of google for timeouts regarding the use of this function.

@fabriziofeitosa

This comment has been minimized.

Copy link

@fabriziofeitosa fabriziofeitosa commented Nov 29, 2019

@srjwebster
I am in the same situation. No solution for multiple uploads.

@srjwebster

This comment has been minimized.

Copy link

@srjwebster srjwebster commented Nov 29, 2019

@srjwebster
I am in the same situation. No solution for multiple uploads.

@fabriziofeitosa I found that by removing some unused media sizes, and by turning off image optimisation plugin wp smush I could run this n a much shorter timeframe. A few seconds compared to several minutes. Definitely not a solution, something asynchronous seems necessary to do this on a frequent basis.

@abhijitaitwade

This comment has been minimized.

Copy link

@abhijitaitwade abhijitaitwade commented May 3, 2020

Script is very good and its worked.

Thanks!!

@ibabul

This comment has been minimized.

Copy link

@ibabul ibabul commented Aug 6, 2020

Life Saver

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.