How to Add Images to Media Library after Uploading them in PHP Programmatically
When you upload files from WordPress admin area, they will automatically appear in Media > Library. But what if you want to create a custom file uploader specially for your website visitors?
All the photos on the screenshot are taken by me in Roza Khutor resort.
Step 1. As usual, we Begin with HTML Form
<form action="<?php echo get_stylesheet_directory_uri() ?>/process_upload.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="profilepicture" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>
What is important to remember here?
- I placed the PHP file
process_upload.php
into the theme directory, if you would like to move it to the other location, do not forget to make changes in the next piece of code on line 4 (I mean code in Step 2). - The form must have
enctype="multipart/form-data"
attribute. Many forget about it.
You can also create a shortcode for this form, just insert this to the functions.php
:
add_shortcode( 'misha_uploader', 'misha_uploader_callback' );
function misha_uploader_callback(){
return '<form action="' . get_stylesheet_directory_uri() . '/process_upload.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="profilepicture" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>';
}
Now you can use just [misha_uploader]
in the editor.
Step 2. Process the Uploaded File in PHP and Add the File Metadata to WordPress Database
This is process_upload.php
file that I decided to create in my current theme directory.
<?php
// WordPress environment
require( dirname(__FILE__) . '/../../../wp-load.php' );
$wordpress_upload_dir = wp_upload_dir();
// $wordpress_upload_dir['path'] is the full server path to wp-content/uploads/2017/05, for multisite works good as well
// $wordpress_upload_dir['url'] the absolute URL to the same folder, actually we do not need it, just to show the link to file
$i = 1; // number of tries when the file with the same name is already exists
$profilepicture = $_FILES['profilepicture'];
$new_file_path = $wordpress_upload_dir['path'] . '/' . $profilepicture['name'];
$new_file_mime = mime_content_type( $profilepicture['tmp_name'] );
if( empty( $profilepicture ) )
die( 'File is not selected.' );
if( $profilepicture['error'] )
die( $profilepicture['error'] );
if( $profilepicture['size'] > wp_max_upload_size() )
die( 'It is too large than expected.' );
if( !in_array( $new_file_mime, get_allowed_mime_types() ) )
die( 'WordPress doesn\'t allow this type of uploads.' );
while( file_exists( $new_file_path ) ) {
$i++;
$new_file_path = $wordpress_upload_dir['path'] . '/' . $i . '_' . $profilepicture['name'];
}
// looks like everything is OK
if( move_uploaded_file( $profilepicture['tmp_name'], $new_file_path ) ) {
$upload_id = wp_insert_attachment( array(
'guid' => $new_file_path,
'post_mime_type' => $new_file_mime,
'post_title' => preg_replace( '/\.[^.]+$/', '', $profilepicture['name'] ),
'post_content' => '',
'post_status' => 'inherit'
), $new_file_path );
// wp_generate_attachment_metadata() won't work if you do not include this file
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate and save the attachment metas into the database
wp_update_attachment_metadata( $upload_id, wp_generate_attachment_metadata( $upload_id, $new_file_path ) );
// Show the uploaded file in browser
wp_redirect( $wordpress_upload_dir['url'] . '/' . basename( $new_file_path ) );
}
Optionally we can set the third parameter of the wp_insert_attachment()
as a parent post ID, and set the featured image of this post with set_post_thumbnail()
.

Misha Rudrastyh
Hey guys and welcome to my website. For more than 10 years I've been doing my best to share with you some superb WordPress guides and tips for free.
Need some developer help? Contact me
You saved my life! thank you thank you thank you so much!!
I’m happy to help, you’re welcome! 🙃
How to upload multiple images?
¡Hola!
Add “[]” to the name of the input tag:
import blob data into wordpress database and assign to custom post
Importing External database blob content into wordpress and assing pdf file into custom post type.
Can anyone help here how to import blob data into wordpress?
Very good code, thank you!
You helped me with my graduation.
I have the following error:
Hey Oliver,
What is your PHP version?
¡Hola Misha! Hi! Gracias, Thank you.
Sorry to bother you, in case you could guide me. I am a photographer and I would like to add many photos to my WP from home.
I have created a function that generates images of different size to the original that my theme needs (66×66, 200×133 …). Thus the weight of the images is much lower than those automatically generated by WP.
To streamline my workflow in WP, I thought about creating a function to upload the images to / wp-content / uploads / 2018/07 via php (now what I do is copy them directly into the folder of the WP installation).
I have also generated a query to the DB to add the necessary information to wp_post and wp_postmeta for each image.
I can use the uploaded image with no problem, I can add it to an entry or page and it looks correctly, both in the WP editor and later on the web.
However, in the WP media gallery the image is not shown to me. It’s like it does not associate the data in the database with the image that I copied in / uploads / 2018/07.
I have noticed and there is no other reference to the images apart from the ones I have already entered in the MYSQL query.
Maybe what I want to do is complex and I should give up. But I would like to at least know where the error may be.
Thanks for your time.
A hug from Granada, Spain.
Hi Alejandro 🙃
Not sure how your function looks like, but I think the code below should help you.
P.S. Never give up 💪
Thank you very much Misha!
Unfortunately I do not know how to implement what you have indicated :(
I do not know how to use the WP functions in my code.
I will try to explain what I have done.
I created a .php out of WP with a connection to a BD (out of WP). I have created a function that runs through a directory with photos to be able to visualize them and move them by assigning an order to the photos and adding that information to the BD (out of WP).
My idea is to generate the content of a post outside of WP, including directly on the WordPress DB the information that I add in my BD (out of WP).
When I read your answer I thought, maybe if I move my .php to the WP installation directory, maybe it will work. But I have to add the WP functions to my .php.
I did it by adding require_once (‘../ wp-load.php’), but if I see my .php in the browser, I get a 404 error code with the appearance of my WP theme.
I get lost here, I have no idea how I could see my page created in .php without the theme, being able to use the functions of WP, for me to be able to test the code that you have given me.
Thank you very much for everything Misha, you have been very kind. I’m sorry I can not put into practice the code you’ve given me, I’m sorry.
A hug.
Oh!
I have discovered define (‘WP_USE_THEMES’, false);
Sorry, at this moment I’m not 100% sure what you’re doing…
Ok, you have a PHP script, you’ve placed it in your WP directory. It is OK, but if it lays directly in WP directory, not in a subfolder, here how to include WP Environment correctly:
Once you included this file, you can place the code I gave you above in it too.
Hi Misha, thank you very much for your time. You’re very kind. “Un tipo cojonudo”. A great guy we say in Spain.
I have tested your code and it works great. What I’m going to do is try to implement it in my code, to see if I’m capable.
Let’s see if I can explain what I want to do. I will be putting a numbered list to see if I explain myself better.
1. I work on localhost with wamp.
2. I have a folder with photos outside of the WordPress installation directory.
3. These photos are the ones I want to add to WordPress. Upload them to the uploads directory.
4. I create a function that runs through the directory of the photos. Could I avoid the form submit? I think that this is the point at which I am not able to implement your code with mine. I do not know exactly how to do it. (Right now I am working on this point).
Thank you very much. Thank you very much.
A hug.
Yes, I understand you correctly.
If you need help with the code, I can write it for you, just contact me.
You are a champion!
This is awesome! It is helping me to finish up a custom plugin I am developing. I have one question: how would I go about displaying the uploaded image using a shortcode?
Hi Melissa,
I need more details.
Please could you help me back giving the snippet for the uploading multiple files from frontend with one fixed featured image and the rest other pictures as in a gallery in WordPress.
Hi,
sure,
If you would like to upload multiple files, you can just add
multiple
attribute to your input field and do not forget to add[]
to the field name.After that you have to process
$_FILES['profilepicture']
as an array.To attach images to a post, add
post_parent
parameter in the second step:To set an image as a featured image, use this:
You are a champion!
how to save uploaded image in custom post type post in custom field?
Hi,
Would you like to save the image ID or url ?
actually i need that uploaded image should be upload in media and custom post type post in custom field
Perfect! But a question, how do I delete the image from the database as soon as the user sends another one?
wp_delete_attachment()
🙃Hey buddy, thank you so much!
Hi
First of all great function I love it!
But I need to have a extra function here instead of
I need a function to say if (empty) the $upload_id = $variable
Will be using it with update_post_meta and not instert_post can you give me a code or point me in the right direction please.
Hi Wilhelm,
So, you would like to have some kind of placeholder here, right?
Thank you so much :)))))
thanks a lot man
i love you
I want to leave a comment because I learn from this. This code save a lot of time and efforts. Thank you so much.