0
votes

I need help with the following: I have created a new <select> button in a WordPress plugin. I want this button in a plugin, when selected, to select image from WordPress media library and upload to a customer form.

In short, I need the admin to be able to change background image of the form by selecting it from the media library.

Button looks like this:

<button>Select Image</button>

Customer form (preview end):

<div id="giftcardForm" style="position:relative;">
    <img src="url" id="background img" style="width:100%; height:auto; z-index:0;">
    <div style="position:absolute; top:$from_y; left:$from_x; width:auto;" id="printname"></div>
    <div style="position:absolute; top:20%; left:$from_x; width:auto;" id="print_to_name"></div>
    <div style="position:absolute; top:30%; left:$from_x; width:auto;" id="showtext"></div>
</div>
2
What is your problem, what is not working?Flummox - don't be evil SE
my problem is, i want to upload an image from wp media library using plugin admin i have set it up, and set it as a background in a form that customer will be filling in.Sele

2 Answers

0
votes
0
votes

You need to give class to your button like:

<button class="media">Select Image</button>

And give proper id to your image tag like

<img src="url" id="background_img" style="width:100%; height:auto; z-index:0;">

After that you need to add following jQuery code which will open select media popup on click of button and set img src which is selected.

jQuery(document).ready(function(){
        var frame = wp.media({
            multiple: true
        });
        jQuery(".media").on("click", function(e) {
            frame.open();
            e.preventDefault();
        });
        frame.on('select', function() {
            var selection = frame.state().get('selection');

            selection.each(function(attachment) {
                jQuery('#background_img').attr('src',attachment.attributes.url);
            });
        });
    });