Upload Files to Media Library Programmatically

When you upload files to your website using media uploader in admin area, WordPress usually handles everything for you. So all the uploaded files automatically appear in WordPress media library and after that can be easily managed, inserted to posts etc.

But when you create some custom functionality, or maybe forms on your website front-end, you should handle it by yourself. And in this tutorial I will show you how.

add images to WordPress media library programatically
It is easier to organize your uploaded images using WordPress Media Library. Photos by me.

In this tutorial we are going to take a look on two scenarios:

  1. When upload images from url (not only images of course),
  2. When upload files using a form.

Upload Images from URL Programmatically

Let’s begin with an image anywhere on the internet. Assuming that we have its URL, and now it is stored in the variable $image_url. How to add it to media library right now?

/**
 * 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 medatata, 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;

}

Upload Files in PHP Using Forms

This part of the tutorial is kind of similar, the only difference is that we are not going to get the file from a remote URL, but upload it ourselves.

1. HTML form

As an example we can upload user profile pictures.

<form action="<?php echo get_stylesheet_directory_uri() ?>/process_upload.php" method="post" enctype="multipart/form-data">
	Your Photo: <input type="file" name="profile_picture" />
	<input type="submit" name="submit" value="Submit" />
</form>

What is recommended to remember here?

  • I placed the PHP file process_upload.php into my theme directory, if you would like to move it to the other location, do not forget to make changes in the following codes as well. If you’re interested in AJAX file uploads, check this tutorial please.
  • 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="profile_picture" />
	<input type="submit" name="submit" value="Submit" />
	</form>';
}

Now you can use just [misha_uploader] in the editor.

2. Process the uploaded file in PHP and add it to media library programmatically

Below is process_upload.php file that I decided to create in my current theme directory.

<?php
// WordPress environmet
require( dirname(__FILE__) . '/../../../wp-load.php' );

// it allows us to use wp_handle_upload() function
require_once( ABSPATH . 'wp-admin/includes/file.php' );

// you can add some kind of validation here
if( empty( $_FILES[ 'profile_picture' ] ) ) {
	wp_die( 'No files selected.' );
}

$upload = wp_handle_upload( 
	$_FILES[ 'profile_picture' ], 
	array( 'test_form' => false ) 
);

if( ! empty( $upload[ 'error' ] ) ) {
	wp_die( $upload[ 'error' ] );
}

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

if( is_wp_error( $attachment_id ) || ! $attachment_id ) {
	wp_die( 'Upload error.' );
}

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

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

// just redirect to the uploaded file
wp_safe_redirect( $upload[ 'url' ] );
exit;

// or you can use update_user_meta() if you're going ot use it as a profile picture

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

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

Follow me on Twitter