Upload Video or Image in WordPress Media Library

Upload Video or Image in WordPress Media Library
1603 Views
4.8
(65)

We’ll learn how to upload files to WordPress programmatically in this article. Perhaps you have already encountered PHP File Upload, but it was clearly broken. It is not advised to use it, even if it does function.

You can programmatically upload files to WordPress using the built-in file uploader. The wp_upload_bits() function, which can be found in wp-includes/functions.php, is the file uploader. The wp-content/uploads/ directory will be where the files are uploaded.

In the WordPress visual editor, you can now use the shortcode [cxc_custom_file_uploader].

<?php
add_shortcode( 'cxc_custom_file_uploader', 'cxc_my_fileUploader_renderer_call_back' );

function cxc_my_fileUploader_renderer_call_back() {
	ob_start();
	$cxc_html = '';
	?>
	<h2>Upload a File</h2>
	<form method="post" enctype="multipart/form-data">
		<input type="file" name="file" required />
		<input type="submit" name="upload_file" value="Upload" />
	</form>
	<?php
	$cxc_html .= ob_get_clean();
	return $cxc_html;
}
?>

WordPress will automatically save your uploaded files inside the uploads directory if you use the wp_upload_bits() method. Your files can be found in the current year-month directory, for instance, wp-content/uploads/2022/12/your_file.

<?php
add_action( 'init', 'cxc_file_upload_by_folder_call_back' );

function cxc_file_upload_by_folder_call_back() {
	if ( isset( $_POST['upload_file'] ) ) {
		$upload = wp_upload_bits($_FILES['file']['name'], null, $_FILES['file']['tmp_name']);
         // save into database $upload['url]
	}
}
?>

You may receive an array containing the directory and URLs of the uploaded files by printing the $upload variable. Using $upload[‘url], users can locate and store these URLs in the database.

As previously indicated, your files will be saved in the standard WordPress folder hierarchy once you use the wp_upload_bits() method. What happens, however, if you want to save files in your own directory?

In that case, you must make a special folder in the uploads directory and transfer your files there. Consider the scenario where you wish to put your files under the uploads/cxc-images directory. You can create the cxc-images folder and put files inside of it using the code provided below.

<?php
add_action( 'init', 'cxc_file_upload_by_folder_call_back' );

function cxc_file_upload_by_folder_call_back() {
	if ( isset( $_POST['upload_file'] ) ) {
		$upload_dir = wp_upload_dir();

		if ( ! empty( $upload_dir['basedir'] ) ) {
			$user_dirname = $upload_dir['basedir'].'/cxc-images';
			if ( ! file_exists( $user_dirname ) ) {
				wp_mkdir_p( $user_dirname );
			}

			$filename = wp_unique_filename( $user_dirname, $_FILES['file']['name'] );
			move_uploaded_file($_FILES['file']['tmp_name'], $user_dirname .'/'. $filename);
             // save into database $upload_dir['baseurl'].'/cxc-images/'.$filename;
		}
	}
}
?>

Alternative solutions

You search the web for wonderful photos that you want to add to your WordPress media library. The method is as follows:

  • Copy the image’s URL.
  • Embed the code below to your site and insert the URL you’ve copied:
<?php
/**
 * Upload image from URL programmatically.
 * Cxc codexcoach
 */
function cxc_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;
}
?>
<?php echo cxc_upload_file_by_url('{{ Enter Your Website Link }}'); ?>

How useful was this blog?

Click on a star to rate it!

Average rating 4.8 / 5. Vote count: 65

No votes so far! Be the first to rate this blog.

Leave a comment

Your email address will not be published. Required fields are marked *