1

I have multiple image user meta fields on the same page and am using a media uploader jquery script to set the URL as the text fields value when the image is clicked.

Works ok on one image field but how can I use over multiple image fields on the same page... ie with ids of ols_user_meta_image_1 through to ols_user_meta_image_5

 jQuery(document).ready(function($){ 
var custom_uploader;



$('.additional-user-image').click(function(e) {

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();
    $('#ols_user_meta_image_1').val(attachment.url);
});

//Open the uploader dialog
custom_uploader.open();

});

So at the moment all fields will inherit the unique id of #ols_user_meta_image_1 value, how can the code be adjusted to allow for a range of image ids.

1

So I set a new variable of target_input that grabs the previous input field ID, this input is where I want the URL of the selected media stored, this is done in the click function of the button that selects the media.

That variable is used to attach the URL.

jQuery(document).ready(function($){


var custom_uploader;
var target_input;


$('.additional-user-image').click(function(e) {
    //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 and add URL
        $( '#' + target_input ).val(attachment.url);
    });

    //Open the uploader dialog
    custom_uploader.open();

});

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.