Skip to content

Instantly share code, notes, and snippets.

@neilgee
Last active January 31, 2021 15:56
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neilgee/0a605a9f731213b7d7bc to your computer and use it in GitHub Desktop.
Save neilgee/0a605a9f731213b7d7bc to your computer and use it in GitHub Desktop.
WordPress Media Uploader For Multiple Images
<?php
/* One of the upload fields as an example */
?>
<tr>
<th><label for="ols_user_meta_image_1"><?php _e( 'OLS Image 1', 'textdomain' ); ?></label></th>
<td>
<!-- Outputs the image after save -->
<img src="<?php echo esc_url( get_the_author_meta( 'ols_user_meta_image_1', $user->ID ) ); ?>" style="width:150px;"><br />
<!-- Outputs the text field and displays the URL of the image retrieved by the media uploader -->
<input type="text" name="ols_user_meta_image_1" id="ols_user_meta_image_1" value="<?php echo esc_url_raw( get_the_author_meta( 'ols_user_meta_image_1', $user->ID ) ); ?>" class="regular-text" />
<!-- Outputs the save button -->
<input type='button' class="additional-user-image button-primary" value="<?php _e( 'Upload Image', 'textdomain' ); ?>" id="uploadimage"/><br />
<span class="description"><?php _e( 'Upload an additional image for your user profile.', 'textdomain' ); ?></span>
</td>
</tr>
jQuery(document).ready(function($){
var custom_uploader;
var target_input;
$('.additional-user-image').click(function(e) {//change class for your common CSS class - this is the button class
//grab the ID of the input field prior to the button where we want the url value stored
target_input = $(this).prev().attr('id');
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
//Added target_input variable to grab ID
$( '#' + target_input ).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment