Skip to content

Instantly share code, notes, and snippets.

@harisrozak
Last active December 13, 2021 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harisrozak/64764a84cd4b3bd7845084572850ba78 to your computer and use it in GitHub Desktop.
Save harisrozak/64764a84cd4b3bd7845084572850ba78 to your computer and use it in GitHub Desktop.
Programmatically add/select terms on WordPress Gutenberg editor
/**
* Programmatically add/select term on Gutenberg editor.
* On this function we are also ready if the classic-editor is loaded.
* Related issue: https://github.com/WordPress/gutenberg/issues/15147
*/
$('.bike-types').on('click', '.bike-type-item', function() {
var tag_id = $( this ).data( 'id' );
var tag_name = $( this ).data( 'name' );
if ( typeof wp !== 'undefined' && typeof wp.blocks !== 'undefined' ) {
var is_tax_panel_opened = wp.data.select( 'core/edit-post' ).isEditorPanelOpened( 'taxonomy-panel-bike-type' );
var selected_ids = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'bike-type' );
var new_ids = [ tag_id ];
// add selected ids if any
for ( var i = 0; i < selected_ids.length; i++ ) {
var new_id = selected_ids[ i ];
if ( ! new_ids.includes( new_id ) ) {
new_ids.push( new_id );
}
}
// update tags
wp.data.dispatch( 'core/editor' ).editPost( { 'bike-type': new_ids } );
// close and re-open the panel to reload the term data
if ( is_tax_panel_opened ) {
wp.data.dispatch( 'core/edit-post' ).toggleEditorPanelOpened( 'taxonomy-panel-bike-type' );
wp.data.dispatch( 'core/edit-post' ).toggleEditorPanelOpened( 'taxonomy-panel-bike-type' );
}
} else {
$( 'input[name="newtag[bike-type]"]' ).val( tag_name ).next().click();
}
return false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment