• Resolved woodwardmatt

    (@woodwardmatt)


    Hi all, I’m attempting to add tags to a post programmatically using a sidebar plugin for the Gutenberg editor. I’m using the following approach:

    var tag_id              = 23;
    var is_tax_panel_opened = wp.data.select( 'core/edit-post' ).isEditorPanelOpened( 'taxonomy-panel-tags' );
    var selected_term_ids   = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'tags' );
    
    // set terms
    if ( ! selected_term_ids.includes( tag_id ) ) {
    	selected_term_ids.push( tag_id );
    	wp.data.dispatch( 'core/editor' ).editPost( { 'tags': selected_term_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-tags' );
    		wp.data.dispatch( 'core/edit-post' ).toggleEditorPanelOpened( 'taxonomy-panel-tags' );
    	}			
    }
    

    Implemented from: https://github.com/WordPress/gutenberg/issues/15147#issuecomment-971715897

    I’m finding that the UI will update to reflect the tags added, the redux store is also updated and contains the tags that have been added. However, if I then update the post (which I have to enable through updating a private metafield otherwise the update button remains disabled until other content is updated too) the UI reloads and the tags have been removed (and not saved).

    Any thoughts?

Viewing 1 replies (of 1 total)
  • Thread Starter woodwardmatt

    (@woodwardmatt)

    *************** SOLVED ***************
    A new JS array must be created from the currently selected items, then your new id added to that also, before passing this back to editPost to update redux with.

    Full solution here.

Viewing 1 replies (of 1 total)
  • The topic ‘Adding Tags Programmatically in Gutenberg’ is closed to new replies.