Custom Image Uploader in WordPress Admin Panel

WordPress gives utmost flexibility to set up whatever you want for your website. These flexibilities does not limit only to the front end but the similar could be done at the backend i.e. the Admin Panel as well.

While creating the posts, pages or custom post types you can add dozens of metaboxes into it. Metaboxes take various types of data from the users with a user friendly UI. Know more about adding metaboxes here.

WordPress helps you take any type of data through metabox format and one of the most needed and tricky to handle is image uploader. When you need images for your custom posts or pages other than the featured images, you can use this metabox to get any number of images from the user.

Custom-Image-Uploader-Wordpress

To begin with we will create a metabox for the WP posts. You can however show this metabox on any page or any type of custom post that you wish. Create a new file to write the code for metabox, here as a reference we are creating ‘image-uploader-metabox.php’.

After creating the file add the below given snippet of code. The function ‘add_image_uploader_metabox()’ will be initiated with hook that we will write in functions.php later. The WP function add_meta_box will create the metabox as per the arguments passed into it.

<?php
function add_image_uploader_metabox()
{	
	add_meta_box(
		'image_uploader_metabox', // Unique ID of metabox
		esc_html__('Image Uploader Metabox', 'textdomain'), //Title of metabox
		'image_uploader_metaboxes', // Callback function
		'post', //name of your custom post type (here post is for wordpress posts.)
		'normal', //Context
		'default' //Priority
	);
}
?>

In the above code we have mentioned ‘image_uploader_metaboxes’ as the callback function. This function will help us generate the HTML of the metabox i.e the visual part how the metabox will appear on the admin side while editing a post. Add the below code to the file that we created.

<?php

//Generate the HTML for uploader links
function image_uploader_metaboxes($object, $box)
{
	wp_nonce_field ( basename ( __FILE__ ), 'image_uploader_metaboxes' );
	
	global $post;
	
	// Get WordPress' media upload URL
	$upload_link = esc_url( get_upload_iframe_src() );
	
	// See if there's a media id already saved as post meta
	$your_img_id = get_post_meta( get_the_ID(), '_your_img_id', true );
	
	// Get the image src
	$your_img_src = wp_get_attachment_image_src( $your_img_id, 'full' );
	
	// For convenience, see if the array is valid
	$you_have_img = is_array( $your_img_src );
	

?>
	<div id="custom-images">
		
		<div class="custom-img-container">
			
			<?php 
				$meta_values = get_post_meta( get_the_ID(), 'image_src', false );
				
				foreach ($meta_values as $value){
			?>
			
			
				<div class="image-wrapper">
					<input type="text" name="image_src[]" value="<?php echo $value;?>">
					<a class="delete-custom-img" href="#">Remove this image</a>
				</div>
				
			<?php }?>
			
		</div>
		
	</div>
		
	<p>
	
	    <a class="upload-custom-img <?php if ( $you_have_img  ) { echo 'hidden'; } ?>" href="<?php echo $upload_link; ?>">
	        <?php _e('Add custom image'); ?>
		</a>
    
	</p>
<?php } ?> <!-- End image_uploader_metaboxes Function -->

The few PHP lines written in the code refer to the image uploading functionality to get the upload link i.e. the WP Media Uploader link, image ID and source. The next portion with the foreach loop will display the path of the image in a text box (if exists) and a remove link next to the textbox.

Below the list of images it shows the add image link, which will open up the WP Media Uploader in a pop up.

After this comes the time to save the metaboxes. Put up the below given code in your file.

<?php

//Save Metadata

function save_image_uploader_metadata( $post_id, $post )
{

	/* Verify the nonce before proceeding. */
		if ( !isset( $_POST['image_uploader_metaboxes'] ) || !wp_verify_nonce( $_POST['image_uploader_metaboxes'], basename( __FILE__ ) ) )
			return $post_id;
		
	/* Get the post type object. */
		$post_type = get_post_type_object( $post->post_type );
	
	/* Check if the current user has permission to edit the post. */
		if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
			return $post_id;
		
	/* Get the meta key. */
		$meta_key = 'image_src';
		
	/* Get the meta value of the custom field key. */
		$meta_value = get_post_meta( $post_id, $meta_key, false );
		
	/* For looping all meta values */
		foreach ($meta_value as $value){
			delete_post_meta( $post_id, $meta_key, $value );
		}
		
	/* Get the posted data and sanitize it for use as an HTML class. */
		foreach($_POST['image_src'] as $value){	
			add_post_meta( $post_id, $meta_key, $value, false );
		}
		
}

?>

Here a variable $meta_key represents the meta key with which the uploaded images will be saved into the database. Here we have used ‘image_src’ as the meta key.

Below this paste the following code which will enqueue the WP Media into the WordPress. The function will be hooked later in this file.

<?php

//For Custom Image Uploader

function enqueue_media(){
	wp_enqueue_media();
}

?>

Now, as the displaying the uploaded image path and hiding or showing the text boxes and remove links are done at the front end. This needs JavaScript to be utilized in the code. The below given function will generate the JavaScript code for the image uploader functionality.

<?php

//JavaScript Code for opening uploader and copying the link of the uploaded image to a textbox

function include_js_code_for_uploader(){
?>

<!-- ****** JS CODE ******  -->
<script>
	jQuery(function($){

	  // Set all variables to be used in scope
	  var frame,
		  metaBox = $('#image_uploader_metabox.postbox'); // Your meta box id here
		  addImgLink = metaBox.find('.upload-custom-img');
		  imgContainer = metaBox.find( '.custom-img-container');
		  imgIdInput = metaBox.find( '.custom-img-id' );
		  customImgDiv = metaBox.find( '#custom-images' );


	  
	  // ADD IMAGE LINK
	  addImgLink.on( 'click', function( event ){
		
		event.preventDefault();
		
		// If the media frame already exists, reopen it.
		if ( frame ) {
		  frame.open();
		  return;
		}
		
		// Create a new media frame
		frame = wp.media({
		  title: 'Select or Upload Media Of Your Chosen Persuasion',
		  button: {
			text: 'Use this media'
		  },
		  multiple: false  // Set to true to allow multiple files to be selected
		});

		
		// When an image is selected in the media frame...
		frame.on( 'select', function() {
		  
		  // Get media attachment details from the frame state
		  var attachment = frame.state().get('selection').first().toJSON();
		  
		  // Send the attachment URL to our custom image input field.
		  imgContainer.append( '<div class="image-wrapper"><input type="text" name="image_src[]" value="'+attachment.url+'"> <a class="delete-custom-img" href="#">Remove this image</a></div>' );
		  
		});

		// Finally, open the modal on click
		frame.open();
	  });

	  
		customImgDiv.on ( 'click', '.delete-custom-img', function (event){		
			event.preventDefault();
			jQuery(event.target).parent().remove();		

		});


	});

</script>

<?php }?>

With the above code snippet, we complete most of the part of our code and the last thing that remains is initiating the functions with their respective hooks. After the above code snippet, paste the below given code. The add_action() function will call the mentioned functions with the hooks mentioned in the first parameter.

<?php

add_action ( 'admin_enqueue_scripts', 'enqueue_media' );

add_action( 'admin_head', 'include_js_code_for_uploader' );

?>

Now its time to initiate our major functions of creating metabox and saving metabox. This will be done in the functions.php file. If you are working in a child theme and it does not have functions.php, creating a new one will help.

Paste the below code at the end of your functions.php:

include('image-uploader-metabox.php');

add_action( 'add_meta_boxes', 'add_image_uploader_metabox' );

add_action( 'save_post', 'save_image_uploader_metadata', 10, 2 );

If your ‘image-uploader-metabox.php’ is not in the same directory as that of the functions.php, you need to change the path mentioned in the above code.

WOLA ! We’re done !

This will create a metabox in your post editing page in the admin panel or in the page or custom post that you have mentioned in the ‘add_image_uploader_metabox()’ function.

Hope this will help you create your custom image uploaders. In case of any queries, comment below. For more such posts follow us on Facebook. 🙂