I am trying to retrieve the tag’s used by the current post in the editor.
Using the console from my browser;
wp.data.select( 'core/editor' ).getEditedPostAttribute( 'tags' )
this will return the used tag id’s but how do I retrieve the actual tags?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use getEntityRecord() like so:
const tag_ids = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'tags' );
// the last parameter is always the tag ID (and just one single ID)
const tag = wp.data.select( 'core' ).getEntityRecord( 'taxonomy', 'post_tag', tag_ids[0] );
console.log( tag ? tag.name : 'still resolving or no such tag..' );
Or use getEntityRecords() with the include parameter set to the tag IDs:
const tag_ids = wp.data.select( 'core/editor' ).getEditedPostAttribute( 'tags' );
// the last parameter is an object containing the REST API endpoint arguments
const tags = wp.data.select( 'core' ).getEntityRecords( 'taxonomy', 'post_tag', { include: tag_ids } );
console.log( tags && tags[0] ? tags[0].name : 'still resolving or tags[0] not available' );
Just remember that getEntityRecord() and getEntityRecords() perform an AJAX request to the /wp/v2/tags route in the REST API, so the functions may not immediately return the response from the API.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0