Skip to content

Instantly share code, notes, and snippets.

@wpexplorer
Created March 15, 2023 08:00
Show Gist options
  • Save wpexplorer/90c3f290d12f44304564bd8eb8ecb627 to your computer and use it in GitHub Desktop.
Save wpexplorer/90c3f290d12f44304564bd8eb8ecb627 to your computer and use it in GitHub Desktop.
Mobile Image Select Button JS
( function() {
const button = document.querySelector( '.wpex-mobile-image-select' );
const field = document.querySelector( '#wpex-mobile-image-input' );
const onButtonClick = ( event ) => {
event.preventDefault();
let send_attachment_bkp = wp.media.editor.send.attachment;
const currentImage = field.value;
const customUploader = wp.media( {
multiple: false
} ).on( 'select', function() {
const attachment = customUploader.state().get( 'selection' ).first().toJSON();
field.value = attachment.id;
} );
customUploader.on( 'open', function() {
if ( currentImage ) {
const selection = customUploader.state().get( 'selection' )
attachment = wp.media.attachment( currentImage );
attachment.fetch();
selection.add( attachment ? [attachment] : [] );
}
} );
customUploader.open();
};
if ( button ) {
button.addEventListener( 'click', onButtonClick );
}
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment