Uploading files to WordPress programmatically

May 18, 2019

If you’re trying to find a way to upload files into WordPress uploads folder/media library programmatically and are tired of all the complex upload_bits methods, you’re in luck. In this article I’m going to show you a few ways to upload files into WordPress programmatically.

These are your options:

The “I need to upload an image, no other file types needed” option

You can use media_sideload_image() function built in WordPress core. Please note that it only accepts files in jpeg, gif and png formats.

<?php

$url = "https://www.example.com/file-url.jpg";
$post_id = 1;
$desc = "Image description";

media_sideload_image($url, $post_id, $desc, 'id');
// Returns image id or WP_Error

The “I need to upload other file types too” option

Put this modified version of the media_sideload_image() into your functions.php, add needed file type extensions to the preg_match and modify it even further if needed:

<?php

function wpa_sideload_file( $file, $post_id = 0, $desc = null ) {
	if( empty( $file ) ) {
		return new \WP_Error( 'error', 'File is empty' );
	}

	$file_array = array();

	// Get filename and store it into $file_array
	// Add more file types if necessary
	preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png|pdf)\b/i', $file, $matches );
	$file_array['name'] = basename( $matches[0] );

	// Download file into temp location.
	$file_array['tmp_name'] = download_url( $file );

	// If error storing temporarily, return the error.
	if ( is_wp_error( $file_array['tmp_name'] ) ) {
		return new \WP_Error( 'error', 'Error while storing file temporarily' );
	}

	// Store and validate
	$id = media_handle_sideload( $file_array, $post_id, $desc );

	// Unlink if couldn't store permanently
	if ( is_wp_error( $id ) ) {
		unlink( $file_array['tmp_name'] );
		return new \WP_Error( 'error', "Couldn't store upload permanently" );
	}

	if ( empty( $id ) ) {
		return new \WP_Error( 'error', "Upload ID is empty" );
	}

	return $id;
}

then just call it like this:

<?php

$url = "https://www.example.com/file-url.jpg";
$post_id = 1; // Use 0 if you don't want to attach the image into a post.
$desc = "File description";

wpa_sideload_file($url, $post_id, $desc);
// Returns image id or WP_Error

Comments

avatar
  Subscribe  
Notify of