WP-Mix

A fresh mix of code snippets and tutorials

WordPress: Simple Image Upload with jQuery

Some of my free WordPress plugins enable users to select and upload files from their local machine. The uploaded images are handled by WordPress and added to the Media Library. The technique is very basic and easy to implement, requiring only a few snippets added to your WordPress site.

Step 1: Add the HTML

First, add the following HTML to your plugin or theme functions file:

<label for="upload_image">Upload Image</label>
<input id="upload_image" name="upload_image" type="text" value="<?php if (isset($options['upload-image'])) echo esc_attr($options['upload-image']); ?>">
<input id="upload_image_button" type="button" value="Upload Image">

You will want to tweak the markup and text to suit your project. Also, the value of the upload field is just the URL of any existing uploaded image. So replace the generic $options['upload-image'] variable with a variable that holds the URL value that should be displayed as the field value.

Step 2: Load the WordPress media scripts

Next, add the following function via your theme functions or simple plugin:

function shapeSpace_load_wp_media_files() {
	
	wp_enqueue_media();
	
}
add_action('admin_enqueue_scripts', 'shapeSpace_load_wp_media_files');

This function simply calls wp_enqueue_media(), which loads all required media assets required for things like image uploads to work.

Step 3: Add the jQuery

Last but not least, add the following snippet of jQuery:

jQuery(document).ready(function($){
	var custom_uploader;
	$('#upload_image_button').click(function(e) {
		e.preventDefault();
		if (custom_uploader) {
			custom_uploader.open();
			return;
		}
		custom_uploader = wp.media.frames.file_frame = wp.media({
			multiple: false,
			library: { type: 'image' },
			button:  { text: 'Select Image' },
			title: 'Select an image or enter an image URL.',
		});
		custom_uploader.on('select', function() {
			console.log(custom_uploader.state().get('selection').toJSON());
			attachment = custom_uploader.state().get('selection').first().toJSON();
			$('#upload_image').val(attachment.url);
		});
		custom_uploader.open();
	});
});

Basically this bit of JavaScript taps into the WP media functionality, so that our humble HTML input field works as a file-upload field. As with the HTML snippet (in step #1), you can customize the specific details like button text, title, and so forth. For more details, check out a live implementation in the source code of my free chat plugin, Simple Ajax Chat.

Cheers! :)

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress