Skip to content

Instantly share code, notes, and snippets.

@rajucs
Created August 20, 2022 08:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajucs/9037f8191495251c484a8f06aec37a0b to your computer and use it in GitHub Desktop.
Save rajucs/9037f8191495251c484a8f06aec37a0b to your computer and use it in GitHub Desktop.
<script>
jQuery(document).ready(function($) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = <?php echo $post->ID; ?>; // Set this
jQuery(document).on('click', '.bk-image-upload', function(event) {
event.preventDefault();
file_frame = '';
var thisBtn = $(this);
var thisBtnSerial = $(this).data('serial')
var nameField = $(this).data('name')
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select images to upload',
button: {
text: 'Add',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on('select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
// thisBtn.find('.bk-floor-image-field').val(attachment.id);
// thisBtn.find('.floor-preview-img').attr('src', attachment.url);
thisBtn.find('.bk-floor-preview-img').html(`
<input type="hidden" name="` + nameField + `" value="` + attachment.id + `">
<img src="` + attachment.url + `" class="floor-preview-img">
`);
// $('.bk-floor-plans-image-' + thisBtnSerial).after('<input type="hidden" name="' + nameField + '" value="' + attachment.id + '">');
// // Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery('a.add_media').on('click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment