jQuery(function ($) { // Set all variables to be used in scope var frame; // ADD IMAGE LINK $(document).on('click', '.service_icon_select_1', function (event) { imgContainer = $(this).parent().find('.bg-img-container'); imgIdInput = $(this).parent().find('.service_icon_select_link'); event.preventDefault(); // If the media frame already exists, reopen it. if (frame) { frame.open(); return; } // Create a new media frame frame = wp.media({ title: 'Select or Upload Image For Title Background', button: { text: 'Select' }, multiple: false // Set to true to allow multiple files to be selected }); // When an image is selected in the media frame... // $(document).on( 'select', 'frame' ,function() { frame.on('select', function () { // Get media attachment details from the frame state var attachment = frame.state().get('selection').first().toJSON(); imgContainer.show(); // Send the attachment URL to our custom image input field. imgContainer.html(''); // Send the attachment id to our hidden input imgIdInput.val(attachment.id).trigger('change'); }); // Finally, open the modal on click frame.open(); }); // Remove IMAGE LINK $(document).on('click', '.service_icon_select_1_remove', function (event) { imgContainer = $(this).parent().find('.bg-img-container'); imgIdInput = $(this).parent().find('.service_icon_select_link'); imgContainer.attr('src', ""); imgContainer.hide(); imgIdInput.val('').trigger('change'); }); });