-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedia.js
52 lines (48 loc) · 1.73 KB
/
media.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
jQuery(function ($) {
// on upload button click
$("body").on("click", ".rudr-upload", function (event) {
event.preventDefault(); // prevent default link click and page refresh
const button = $(this);
const imageId = button.next().next().val();
const customUploader = wp
.media({
title: "Insert image", // modal window title
library: {
// uploadedTo : wp.media.view.settings.post.id, // attach to the current post?
type: "image",
},
button: {
text: "Use this image", // button label text
},
multiple: false,
})
.on("select", function () {
// it also has "open" and "close" events
const attachment = customUploader
.state()
.get("selection")
.first()
.toJSON();
button.removeClass("button").html('<img src="' + attachment.url + '">'); // add image instead of "Upload Image"
button.next().show(); // show "Remove image" link
button.next().next().val(attachment.id); // Populate the hidden field with image ID
});
// already selected images
customUploader.on("open", function () {
if (imageId) {
const selection = customUploader.state().get("selection");
attachment = wp.media.attachment(imageId);
attachment.fetch();
selection.add(attachment ? [attachment] : []);
}
});
customUploader.open();
});
// on remove button click
$("body").on("click", ".rudr-remove", function (event) {
event.preventDefault();
const button = $(this);
button.next().val(""); // emptying the hidden field
button.hide().prev().addClass("button").html("Upload image"); // replace the image with text
});
});