neilgee
2/28/2016 - 6:32 AM

WordPress Media Uploader For Multiple Images

WordPress Media Uploader For Multiple Images

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


    var custom_uploader;
    var target_input;


    $('.additional-user-image').click(function(e) {//change class for your common CSS class - this is the button class
        //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
            $( '#' + target_input ).val(attachment.url);
        });

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

    });
<?php
/* One of the upload fields as an example */

?>
<tr>
            <th><label for="ols_user_meta_image_1"><?php _e( 'OLS Image 1', 'textdomain' ); ?></label></th>
            <td>
                <!-- Outputs the image after save -->
                <img src="<?php echo esc_url( get_the_author_meta( 'ols_user_meta_image_1', $user->ID ) ); ?>" style="width:150px;"><br />
                <!-- Outputs the text field and displays the URL of the image retrieved by the media uploader -->
                <input type="text" name="ols_user_meta_image_1" id="ols_user_meta_image_1" value="<?php echo esc_url_raw( get_the_author_meta( 'ols_user_meta_image_1', $user->ID ) ); ?>" class="regular-text" />
                <!-- Outputs the save button -->
                <input type='button' class="additional-user-image button-primary" value="<?php _e( 'Upload Image', 'textdomain' ); ?>" id="uploadimage"/><br />
                <span class="description"><?php _e( 'Upload an additional image for your user profile.', 'textdomain' ); ?></span>
            </td>
        </tr>