pda-wordpress-upload-file-programmatically

WordPress Upload File Programmatically: 3 Practical Ways

By default, WordPress supports uploading files via its media library or post edit screen. When you upload files to your website using these built-in functions, WordPress handles everything for you. It allows you to view all the uploaded files and insert them into your posts or pages.

However, you need more than that when it comes to custom functionalities, such as frontend file uploads. There are plenty of plugins available that help you add, modify, and manage your files without adjusting code. Of course, most of them require a fee.

If you don’t want to pay for plugins, uploading files programmatically to your WordPress site can be a solution. In this article, we’ll guide you on how to achieve that in detail.

Let’s get started!

A Little Notice

This method mainly interferes with code. So, please opt-in to this technique only if you have some coding knowledge. Otherwise, your entire site can collapse with just one small improper change.

Before you read further.... Free Download (PDF)

Secret Side Door

Secret Google Search Tactic That Will Skyrocket Your Sales, Connect You to the Perfect Partners, Influencers & Affiliates and Send Your Google Rankings Soaring! FREE when you sign up for Digital Creators Edge, a free newsletter for Digital Creators who wish to take their business to the next level.

In case you’ve just started with WordPress, we highly recommend the Gravity Forms plugin to accept frontend file uploads. Or, check out the top 5 plugins for WordPress frontend file uploads. You can also use an FTP client to upload files from the backend.

Still, want to learn how to upload files programmatically in WordPress? Keep reading!

#1 Upload Files to Media Library Programmatically from URLs

You browse the internet and find great images that you desire to upload to your WordPress media library. Here’s the route to do so:

  1. Copy the image’s URL.
  2. Embed the code below to your site and insert the URL you’ve copied:
/**
* Upload image from URL programmatically
*
* @author Misha Rudrastyh
* @link https://rudrastyh.com/wordpress/how-to-add-images-to-media-library-from-uploaded-files-programmatically.html#upload-image-from-url
*/
function rudr_upload_file_by_url( $image_url ) {

// it allows us to use download_url() and wp_handle_sideload() functions
require_once( ABSPATH . 'wp-admin/includes/file.php' );

// download to temp dir

$temp_file = download_url( $image_url );

if( is_wp_error( $temp_file ) ) {
return false;
}

// move the temp file into the uploads directory
$file = array(
'name'     => basename( $image_url ),
'type'     => mime_content_type( $temp_file ),
'tmp_name' => $temp_file,
'size'     => filesize( $temp_file ),
);
$sideload = wp_handle_sideload(
$file,
array(
'test_form'   => false // no needs to check 'action' parameter
)
);

if( ! empty( $sideload[ 'error' ] ) ) {
// you may return error message if you want
return false;
}

// it is time to add our uploaded image into WordPress media library
$attachment_id = wp_insert_attachment(
array(
'guid'           => $sideload[ 'url' ],
'post_mime_type' => $sideload[ 'type' ],
'post_title'     => basename( $sideload[ 'file' ] ),
'post_content'   => '',
'post_status'    => 'inherit',
),
$sideload[ 'file' ]
);

if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
return false;
}

// update metadata, regenerate image sizes
require_once( ABSPATH . 'wp-admin/includes/image.php' );

wp_update_attachment_metadata(
$attachment_id,
wp_generate_attachment_metadata( $attachment_id, $sideload[ 'file' ] )
);

return $attachment_id;
}

That’s it!

#2 Add Files via an HTML Form

The second method is to create a simple HTML form with file input and submit button. You can place this form on any page or post, which allows users to upload files to your site. Take the following steps to upload files programmatically in WordPress via an HTML form:

  1. Embed the following code to build a simple HTML form:
1 <h2>Upload a File</h2>
2 <form method="post" enctype="multipart/form-data">
3     <input type="file" name="file" required />
4     <input type="submit" name="upload_file" value="Upload" />
5 </form>

By using the wp_upload_bits() function, WordPress will automatically store your uploaded files inside the uploads directory. You can find your files inside the current year-month folder, for example, wp-content/uploads/2020->03->your_file.

2. Insert this code in your functions.php file:

1 <?php
2 function fn_upload_file() {
3     if ( isset($_POST['upload_file']) ) {
4         $upload = wp_upload_bits($_FILES['file']['name'], null, $_FILES['file']['tmp_name']);
5         // save into database $upload['url]
6     }
7 }
8 add_action('init', 'fn_upload_file');

If you print the $upload variable, you’ll get an array which contains the directory and the uploaded files’ URLs. Users can find and save these URLs in the database using $upload[‘url].

As mentioned above, once using the wp_upload_bits() method, your files will be stored in the default WordPress folder hierarchy. But what if you wish to save files inside your own directory?

In that situation, you should create a custom folder in the uploads directory and move files into it. Let’s say you want to store your files inside the uploads/product-images directory. With the code below, you can generate the product-images folder and store files inside it.

Write the code in the functions.php file:

1 function fn_upload_file() {
2     if ( isset($_POST['upload_file']) ) {
3         $upload_dir = wp_upload_dir();
4
5         if ( ! empty( $upload_dir['basedir'] ) ) {
6             $user_dirname = $upload_dir['basedir'].'/product-images';
7             if ( ! file_exists( $user_dirname ) ) {
8                 wp_mkdir_p( $user_dirname );
9             }
10
11             $filename = wp_unique_filename( $user_dirname, $_FILES['file']['name'] );
12             move_uploaded_file($_FILES['file']['tmp_name'], $user_dirname .'/'. $filename);
13             // save into database $upload_dir['baseurl'].'/product-images/'.$filename;
14         }
15     }
16 }
17 add_action('init', 'fn_upload_file');

Here, we’re applying the wp_unique_filename() technique to give a unique filename to the given directory.

Let’s assume that you have a gallery added as a custom meta field called “gallery”. You upload plenty of images through the media_sideload_image(). Then, serialize their IDs and insert them to the gallery by update_post_meta( $post_id , ‘gallery’, $serialized);

Consequently, when you look at the post in the backend Edit post page, you’ll see all the uploaded photos. However, these pictures won’t show in a slideshow in the frontend until you hit Update in the backend.

So, how can you programmatically click the Update button after you’ve created the gallery? Simply follow the guide below:

  1. Once you update the post gallery, add this code to programmatically select the Update button:
wp_update_post(['ID'=>$post_id]);

2. Update the cache to use the search and filter functions:

do_action('search_filter_update_post_cache', $post_id);

Bonus Tip: Protect Your File Uploads

Are there any ways to prevent unauthorized access to your uploaded files? The answer is yes. For more information, please refer to our detailed guide on 21 useful .htaccess tricks to secure WordPress files. Since .htaccess is a critical file that keeps your site running smoothly, be cautious when making any changes.

On the other hand, install the PDA Gold plugin if you aren’t confident in your coding skills. It will help you handle the hassle without worrying about affecting the .htaccess file.

Another worth-considering method is to password protect your WordPress files. Check out our article for more details.

Upload Files Programmatically in WordPress Like an Expert!

We’ve shown you 3 ways to upload files programmatically in WordPress. Now, you can effortlessly upload files to the media library or via an HTML frontend file upload form. It’s also achievable to add files to your custom gallery. And most importantly, don’t forget to protect your WordPress files either using code or installing plugins.

It’s all about how to upload files programmatically in WordPress. Do you know any other methods? Please share with us in the comment section below.