Skip to content

Instantly share code, notes, and snippets.

@landbryo
Created April 17, 2023 17:27
Show Gist options
  • Save landbryo/b477b0daa2fb437f44d3ac73e869c3f5 to your computer and use it in GitHub Desktop.
Save landbryo/b477b0daa2fb437f44d3ac73e869c3f5 to your computer and use it in GitHub Desktop.
Adds image upload to a single term in the WP admin.
/* global jQuery */
/**
* Styles
*/
import './term.scss';
( () => {
const {
i18n: { __ },
} = wp;
let featuredImage;
// Wait for DOM to be ready.
window.addEventListener( 'DOMContentLoaded', init );
const handleFeaturedImage = () => {
const uploadButton = featuredImage.querySelector( '.button.upload' );
const removeButton = featuredImage.querySelector( '.button.remove' );
const image = featuredImage.querySelector( '.image' );
const input = featuredImage.querySelector( 'input' );
// Determine initial button state.
if ( featuredImage.classList.contains( 'full' ) ) {
uploadButton.style.display = 'none';
} else {
removeButton.style.display = 'none';
}
// Handle the remove button click.
removeButton.addEventListener( 'click', ( e ) => {
e.preventDefault();
image.setAttribute( 'src', '' );
input.setAttribute( 'value', 0 );
removeButton.style.display = 'none';
uploadButton.style.display = 'inline-block';
} );
// Trigger with jQuery so internal events work as WP intended.
jQuery( uploadButton ).on( 'click', ( e ) => {
e.preventDefault();
handleMediaUploaderEvent();
} );
jQuery( image ).on( 'click', ( e ) => handleMediaUploaderEvent( e ) );
/**
* Handle the event which creates and opens the media uploader.
*/
const handleMediaUploaderEvent = () => {
// Create uploader instance.
const uploader = wp.media( {
title: __( 'Insert image', 'plugin-core' ),
library: {
type: 'image',
},
button: {
text: __( 'Use image', 'plugin-core' ),
},
multiple: false,
} );
// Select/save event when image has been chosen.
uploader.on( 'select', () => {
const attachment = uploader
.state()
.get( 'selection' )
.first()
.toJSON();
image.setAttribute( 'src', attachment.sizes.thumbnail.url );
input.setAttribute( 'value', attachment.id );
// Change button state.
removeButton.style.display = 'inline-block';
uploadButton.style.display = 'none';
} );
uploader.on( 'close', () => {
// Remove uploader instance.
uploader.remove();
} );
// Open the uploader.
uploader.open();
};
};
/**
* Initialize after DOM is loaded.
*/
function init() {
featuredImage = document.querySelector( '#plugin-featured-image' );
if ( featuredImage ) {
handleFeaturedImage();
}
}
} )();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment