Customizable Media Uploader in WordPress admin area

In this post I will show you how to create beautiful, simple and customizable media uploader for your WordPress website.

#attachments, #metas, #wp-admin  /  April 12  /   19

Sometimes it is required to create a simple and intuitive graphic interface for the clients that allows to upload images or another files for posts or in website settings without problems.

For me it is enough if the website settings has a text input field where I can place the image URL. But it is not enough for the regular user. It is even not professional — that’s what I think.

In this post I will show you how to create a beautiful, simple and customizable media uploader for your website.

Before we begin: Upload Button Demonstration #

As an example I use the website of one of my clients, with his permission of course.

And here is how the button looks like. Clean and really simple.

Upload Image button in WordPress admin area

If you click on the Upload image button, WordPress media uploader popup window will appear. In this window you can choose one of the previous uploaded images or upload a new one.

WordPress media uploader popup with the image selected

Some customization options:

  • you can change the title of the media library popup ( Insert image ) and the label of the button ( Use this image ),
  • you can also configure in the code easily if you want to attach the uploaded image to the current post or not,
  • multimple image selection is allowed as well but it requires some additional code.

If the image is selected, you can click on it to choose another one or remove it by clicking Remove image link.

If the image is selected, you can click on it to choose another one.

And below is my instruction.

3 easy steps of Creating the Upload Image Button on your Own Website #

Step 1. jQuery code #

If you do not know much about jQuery, create an empty .js file in your current WordPress theme folder and place the following code there. Otherwise you can even skip the second step.

jQuery(function($){
	/*
	 * Select/Upload image(s) event
	 */
	$('body').on('click', '.misha_upload_image_button', function(e){
		e.preventDefault();
 
    		var button = $(this),
    		    custom_uploader = wp.media({
			title: 'Insert image',
			library : {
				// uncomment the next line if you want to attach image to the current post
				// uploadedTo : wp.media.view.settings.post.id, 
				type : 'image'
			},
			button: {
				text: 'Use this image' // button label text
			},
			multiple: false // for multiple image selection set to true
		}).on('select', function() { // it also has "open" and "close" events 
			var attachment = custom_uploader.state().get('selection').first().toJSON();
			$(button).removeClass('button').html('<img class="true_pre_image" src="' + attachment.url + '" style="max-width:95%;display:block;" />').next().val(attachment.id).next().show();
			/* if you sen multiple to true, here is some code for getting the image IDs
			var attachments = frame.state().get('selection'),
			    attachment_ids = new Array(),
			    i = 0;
			attachments.each(function(attachment) {
 				attachment_ids[i] = attachment['id'];
				console.log( attachment );
				i++;
			});
			*/
		})
		.open();
	});
 
	/*
	 * Remove image event
	 */
	$('body').on('click', '.misha_remove_image_button', function(){
		$(this).hide().prev().val('').prev().addClass('button').html('Upload image');
		return false;
	});
 
});

Step 2. Enqueue scripts into admin area using wp_enqueue_script() and wp_enqueue_media() #

We need this piece of code to add our jQuery script to WordPress admin area. Insert it to your current theme functions.php file.

function misha_include_myuploadscript() {
	/*
	 * I recommend to add additional conditions just to not to load the scipts on each page
	 * like:
	 * if ( !in_array('post-new.php','post.php') ) return;
	 */
	if ( ! did_action( 'wp_enqueue_media' ) ) {
		wp_enqueue_media();
	}
 
 	wp_enqueue_script( 'myuploadscript', get_stylesheet_directory_uri() . '/customscript.js', array('jquery'), null, false );
}
 
add_action( 'admin_enqueue_scripts', 'misha_include_myuploadscript' );

Step 3. Ready-to-use PHP function #

Insert this function to functions.php file as well.

/*
 * @param string $name Name of option or name of post custom field.
 * @param string $value Optional Attachment ID
 * @return string HTML of the Upload Button
 */
function misha_image_uploader_field( $name, $value = '') {
	$image = ' button">Upload image';
	$image_size = 'full'; // it would be better to use thumbnail size here (150x150 or so)
	$display = 'none'; // display state ot the "Remove image" button
 
	if( $image_attributes = wp_get_attachment_image_src( $value, $image_size ) ) {
 
		// $image_attributes[0] - image URL
		// $image_attributes[1] - image width
		// $image_attributes[2] - image height
 
		$image = '"><img src="' . $image_attributes[0] . '" style="max-width:95%;display:block;" />';
		$display = 'inline-block';
 
	} 
 
	return '
	<div>
		<a href="#" class="misha_upload_image_button' . $image . '</a>
		<input type="hidden" name="' . $name . '" id="' . $name . '" value="' . $value . '" />
		<a href="#" class="misha_remove_image_button" style="display:inline-block;display:' . $display . '">Remove image</a>
	</div>';
}

That’s it. Now we can use the button in our post meta boxes or option pages. If this code doesn’t seems simple for you, please look at this ready solution.

Example 1. Media Uploader in Post Meta Boxes #

Yes, yes, yes, this code is also for your functions.php file.

/*
 * Add a meta box
 */
add_action( 'admin_menu', 'misha_meta_box_add' );
 
function misha_meta_box_add() {
	add_meta_box('mishadiv', // meta box ID
		'More settings', // meta box title
		'misha_print_box', // callback function that prints the meta box HTML 
		'post', // post type where to add it
		'normal', // priority
		'high' ); // position
}
 
/*
 * Meta Box HTML
 */
function misha_print_box( $post ) {
	$meta_key = 'second_featured_img';
	echo misha_image_uploader_field( $meta_key, get_post_meta($post->ID, $meta_key, true) );
}
 
/*
 * Save Meta Box data
 */
add_action('save_post', 'misha_save');
 
function misha_save( $post_id ) {
	if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) 
		return $post_id;
 
	$meta_key = 'second_featured_img';
 
	update_post_meta( $post_id, $meta_key, $_POST[$meta_key] );
 
	// if you would like to attach the uploaded image to this post, uncomment the line:
	// wp_update_post( array( 'ID' => $_POST[$meta_key], 'post_parent' => $post_id ) );
 
	return $post_id;
}

Example 2. Media Uploader in Options Pages #

Code for functions.php:

add_action('admin_menu', 'misha_add_options_page');
 
function misha_add_options_page() {
	$page_slug = 'uplsettings';
	$option_name = 'header_img';
 
	if ( isset( $_GET['page'] ) && $_GET['page'] == $page_slug ) {
		if ( isset( $_REQUEST['action'] ) && 'save' == $_REQUEST['action'] ) {
			update_option( $option_name, $_REQUEST[ $option_name ] );
			header('Location: '. site_url() .'/wp-admin/options-general.php?page=' . $page_slug . '&saved=true');
			die;
		}
	}
	add_submenu_page('options-general.php','More settings','More settings (title)', 'edit_posts', $page_slug, 'misha_print_options_page');
}
 
function misha_print_options_page() {
 
	$option_name = 'header_img';
 
	if ( isset( $_REQUEST['saved'] ) ){
		echo '<div class="updated"><p>Saved.</p></div>';
	}
	echo '<div class="wrap"><form method="post">'
	. misha_image_uploader_field( $option_name, get_option( $option_name ) )
	. '<p class="submit">
		<input name="save" type="submit" class="button-primary" value="Save changes" />
		<input type="hidden" name="action" value="save" />
		</p></form></div>';
}

Example 3. Much more simple solution with my plugin #

First of all you have to download this plugin and install it on you WordPress website.

Download the plugin

In Meta Box

Look how simple it is to add an upload button to post meta boxes (code for functions.php):

new trueMetaBox( array(
		'id'	=>	'misha', // metabox ID, this is also used as custom field prefix
		'name'	=>	'Metabox with the image upload button', // title
		'post_type'	=> array('page'), // post types here
		'priority'	=> 'high', // low | high | default
		'capability'=>	'edit_posts', // capabilities the user should have to edit this metabox
		'args'	=>	array(
 
			array(
				'id'		=> 'img',
				'label'		=> 'Image',
				'description'	=> 'The upload button description should be here.',
				'type'		=> 'image'
			)
 
		)
	)
);

The result:

Upload Image Meta Box in WordPress using my plugin

In Options Page

And this is how to add an Upload button to Settings > General.

new trueOptionspage( array(
	'slug'		=> 'general',
	'sections' 	=> array(
 		array(
			'id'	=> 'default',
			'fields'=> array(
				array(
					'id'		=> 'img1',
					'label'		=> 'Custom image in setting',
					'description'	=> 'Your custom description is here.',
					'type'		=> 'image'
				)
 			)
		) 
	)
));
Image Upload Button in WordPress general settings.

If you have a question, please leave it in comments.

Only the best of WordPress

Subscribe to this weekly newsletter to receive the latest blog posts by email.I respect your privacy. Your email is safe with me.

Comments 19

  • Hi, it’s possible upload multiple image and save an array in a metadata field, like the most popular real estate site?

  • Hello Misha, thanks for your answer.
    You’re using your scripts to manage the image gallery of a site of a real estate agency. I have two questions to ask yourself:
    you can after you upload the images to manage them in administration, one by one? Now it is only seen her picture and I have no chance to toglierne or add, then if I click on “remove image” takes it from me by the administration but not from the site
    In the plugin there are other features?

    Thank you.

  • frame is not defined while using multiple image uploading

    • MishaAuthor October 14, 2016 at 09:01

      Please describe me what you did.

      • $('body').on('click', '.<?php echo $name; ?>_add_gallery', function(e){
        					e.preventDefault();
        						var btn_name = $(this).attr('data-name');
        						var button = $(this),
        							custom_uploader = wp.media({
        						title: 'Insert image',
        						library : {
        							// uncomment the next line if you want to attach image to the current post
        							// uploadedTo : wp.media.view.settings.post.id, 
        							type : 'image'
        						},
        						button: {
        							text: 'Use this image' // button label text
        						},
        						multiple: true // for multiple image selection set to true
        					}).on('select', function() { // it also has "open" and "close" events 
        						var attachment = custom_uploader.state().get('selection').first().toJSON();
        						var attachments = frame.state().get('selection'),
        							attachment_ids = '',gallery_image;
         
        						attachments.each(function(attachment) {
        							if(attachment_ids == '')
        								attachment_ids += attachment['id'];
        							else
        								attachment_ids += ','+attachment['id'];
        							$(btn_name+'_image_container').append('<img class="true_pre_image" src="' + attachment['url'] + '" />');
        						});
        						$(btn_name+'_hidden').val(attachment_ids);
        					})
        					.open();
        				});

        frame is not defined message showing in console.

        • MishaAuthor October 14, 2016 at 15:31

          You just set multiple parameter to true, right? Is that all?

          • yes.

            multiple : true

            for selecting multiple image.

            and in this code (

            frame.state().get('selection')

            ), i cann’t see where the

            frame

            defined ?

          • MishaAuthor October 16, 2016 at 13:48

            After turning on multiple attribute you should change the other code as well. console.log() should help you with that.

  • replace the keyword

    frame

    from

    custom_uploader
  • How do I see what the link in the image is?

  • hey, using this method, do the images get attached to a post? via a meta box….
    Not just an id in the post meta, but actually get attached to the post.

  • Hey Misha,
    Great tutorial, though I’m stuck with one feature. After altering the “multiple: true” variable how do I then display an extra upload button on the posts admin page.
    Do I just duplicate some part of the misha_image_uploader_field function for each uploader I need or is it something more complicated?

    Someone already asked something similar above but the question and answers didn’t really help.

    Thanks again.

    • MishaAuthor May 2, 2017 at 08:40

      Hi Robert,

      multiple:true just should allow the multiple image selection in popup. After activating this option you can try to add in onselect event something like this.

      var attachments = custom_uploader.state().get('selection').toJSON();
      console.log( attachments );

Leave your question or feedback

phpjsHTMLCSSSQLCode
Please, enter a comment
Please, enter a name
Incorrect email