Using WordPress Media Library Loader Twice in Same Form
-
I am working on a plugin where I have to use WordPress media library loader twice in a same form in WordPress option.
in my code I have two image as button for media library loader.also hidden input field to retrieve the value of user selected image from media library.
But when I open and close a media loader and open another one.there are some conflict with both media loader as they are loaded and hided with display:none. so when I save the form there are many bug because of this conflict.I used ‘off’ listener in jQuery to prevent this also updated my code with the help of chatGPT but its always not working.here is my js code:-
/**
* Media Uploader
*/
(function($) {
class SimpleCharm_portfolio_Media {
constructor() {
this.init();
}
init() {
this.mediaUploader('simplecharm-portfolio-user-image', "simplecharm_portfolio_user_image","Upload Image");
this.mediaUploader('simplecharm-portfolio-user-image2', "simplecharm_portfolio_user_image2", "Upload Another Image");
}
mediaUploader(picked_image, hidden_field,custom_text = 'Upload Image') {
let image = null;
$(.${picked_image}
).on('keyup', function(e) {
if ($(e.keyCode)[0] !== 13) return;
e.target.click();
})
$(.${picked_image}
).off('click').on('click', function(e) {
e.preventDefault();
if (image) {
image.off("select");
image.close();
}
image = wp.media({
title: custom_text,
multiple: false, // Set to true if you want to upload multiple files at once
library: {
type: 'image' // Only load image files
}
}).open().on('select', function() {
// This will return the selected image from the Media Uploader, the result is an object
let uploaded_image = image.state().get('selection').first();
// Convert uploaded_image to a JSON object to make accessing it easier
let image_url = uploaded_image.toJSON().url;
// Assign the url value to the image and hidden input field
$(.${picked_image}
).attr("src", image_url);
$(.${hidden_field}
).val(image_url);
});
image.open();
});
}
}
new SimpleCharm_portfolio_Media();
})(jQuery);
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Using WordPress Media Library Loader Twice in Same Form’ is closed to new replies.