Last active
January 31, 2021 15:56
-
-
Save neilgee/0a605a9f731213b7d7bc to your computer and use it in GitHub Desktop.
WordPress Media Uploader For Multiple Images
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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