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.

  1. <?php
  2. function add_image_uploader_metabox()
  3. {	
  4. 	add_meta_box(
  5. 		'image_uploader_metabox', // Unique ID of metabox
  6. 		esc_html__('Image Uploader Metabox', 'textdomain'), //Title of metabox
  7. 		'image_uploader_metaboxes', // Callback function
  8. 		'post', //name of your custom post type (here post is for wordpress posts.)
  9. 		'normal', //Context
  10. 		'default' //Priority
  11. 	);
  12. }
  13. ?>

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.

  1. <?php
  2.  
  3. //Generate the HTML for uploader links
  4. function image_uploader_metaboxes($object, $box)
  5. {
  6. 	wp_nonce_field ( basename ( __FILE__ ), 'image_uploader_metaboxes' );
  7.  
  8. 	global $post;
  9.  
  10. 	// Get WordPress' media upload URL
  11. 	$upload_link = esc_url( get_upload_iframe_src() );
  12.  
  13. 	// See if there's a media id already saved as post meta
  14. 	$your_img_id = get_post_meta( get_the_ID(), '_your_img_id', true );
  15.  
  16. 	// Get the image src
  17. 	$your_img_src = wp_get_attachment_image_src( $your_img_id, 'full' );
  18.  
  19. 	// For convenience, see if the array is valid
  20. 	$you_have_img = is_array( $your_img_src );
  21.  
  22.  
  23. ?>
  24. 	<div id="custom-images">
  25.  
  26. 		<div class="custom-img-container">
  27.  
  28. 			<?php 
  29. 				$meta_values = get_post_meta( get_the_ID(), 'image_src', false );
  30.  
  31. 				foreach ($meta_values as $value){
  32. 			?>
  33.  
  34.  
  35. 				<div class="image-wrapper">
  36. 					<input type="text" name="image_src[]" value="<?php echo $value;?>">
  37. 					<a class="delete-custom-img" href="#">Remove this image</a>
  38. 				</div>
  39.  
  40. 			<?php }?>
  41.  
  42. 		</div>
  43.  
  44. 	</div>
  45.  
  46. 	<p>
  47.  
  48. 	    <a class="upload-custom-img <?php if ( $you_have_img  ) { echo 'hidden'; } ?>" href="<?php echo $upload_link; ?>">
  49. 	        <?php _e('Add custom image'); ?>
  50. 		</a>
  51.  
  52. 	</p>
  53. <?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.

  1. <?php
  2.  
  3. //Save Metadata
  4.  
  5. function save_image_uploader_metadata( $post_id, $post )
  6. {
  7.  
  8. 	/* Verify the nonce before proceeding. */
  9. 		if ( !isset( $_POST['image_uploader_metaboxes'] ) || !wp_verify_nonce( $_POST['image_uploader_metaboxes'], basename( __FILE__ ) ) )
  10. 			return $post_id;
  11.  
  12. 	/* Get the post type object. */
  13. 		$post_type = get_post_type_object( $post->post_type );
  14.  
  15. 	/* Check if the current user has permission to edit the post. */
  16. 		if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
  17. 			return $post_id;
  18.  
  19. 	/* Get the meta key. */
  20. 		$meta_key = 'image_src';
  21.  
  22. 	/* Get the meta value of the custom field key. */
  23. 		$meta_value = get_post_meta( $post_id, $meta_key, false );
  24.  
  25. 	/* For looping all meta values */
  26. 		foreach ($meta_value as $value){
  27. 			delete_post_meta( $post_id, $meta_key, $value );
  28. 		}
  29.  
  30. 	/* Get the posted data and sanitize it for use as an HTML class. */
  31. 		foreach($_POST['image_src'] as $value){	
  32. 			add_post_meta( $post_id, $meta_key, $value, false );
  33. 		}
  34.  
  35. }
  36.  
  37. ?>

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.

  1. <?php
  2.  
  3. //For Custom Image Uploader
  4.  
  5. function enqueue_media(){
  6. 	wp_enqueue_media();
  7. }
  8.  
  9. ?>

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.

  1. <?php
  2.  
  3. //JavaScript Code for opening uploader and copying the link of the uploaded image to a textbox
  4.  
  5. function include_js_code_for_uploader(){
  6. ?>
  7.  
  8. <!-- ****** JS CODE ******  -->
  9. <script>
  10. 	jQuery(function($){
  11.  
  12. 	  // Set all variables to be used in scope
  13. 	  var frame,
  14. 		  metaBox = $('#image_uploader_metabox.postbox'); // Your meta box id here
  15. 		  addImgLink = metaBox.find('.upload-custom-img');
  16. 		  imgContainer = metaBox.find( '.custom-img-container');
  17. 		  imgIdInput = metaBox.find( '.custom-img-id' );
  18. 		  customImgDiv = metaBox.find( '#custom-images' );
  19.  
  20.  
  21.  
  22. 	  // ADD IMAGE LINK
  23. 	  addImgLink.on( 'click', function( event ){
  24.  
  25. 		event.preventDefault();
  26.  
  27. 		// If the media frame already exists, reopen it.
  28. 		if ( frame ) {
  29. 		  frame.open();
  30. 		  return;
  31. 		}
  32.  
  33. 		// Create a new media frame
  34. 		frame = wp.media({
  35. 		  title: 'Select or Upload Media Of Your Chosen Persuasion',
  36. 		  button: {
  37. 			text: 'Use this media'
  38. 		  },
  39. 		  multiple: false  // Set to true to allow multiple files to be selected
  40. 		});
  41.  
  42.  
  43. 		// When an image is selected in the media frame...
  44. 		frame.on( 'select', function() {
  45.  
  46. 		  // Get media attachment details from the frame state
  47. 		  var attachment = frame.state().get('selection').first().toJSON();
  48.  
  49. 		  // Send the attachment URL to our custom image input field.
  50. 		  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>' );
  51.  
  52. 		});
  53.  
  54. 		// Finally, open the modal on click
  55. 		frame.open();
  56. 	  });
  57.  
  58.  
  59. 		customImgDiv.on ( 'click', '.delete-custom-img', function (event){		
  60. 			event.preventDefault();
  61. 			jQuery(event.target).parent().remove();		
  62.  
  63. 		});
  64.  
  65.  
  66. 	});
  67.  
  68. </script>
  69.  
  70. <?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.

  1. <?php
  2.  
  3. add_action ( 'admin_enqueue_scripts', 'enqueue_media' );
  4.  
  5. add_action( 'admin_head', 'include_js_code_for_uploader' );
  6.  
  7. ?>

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:

  1. include('image-uploader-metabox.php');
  2.  
  3. add_action( 'add_meta_boxes', 'add_image_uploader_metabox' );
  4.  
  5. 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. 🙂

Related Post

2 thoughts on “Custom Image Uploader in WordPress Admin Panel

Comments are closed.