最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using wp.data.select get actual tags (not id's) used in post

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Feb 21, 2021 at 16:11 LeadhoodLeadhood 375 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

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.

发布评论

评论列表(0)

  1. 暂无评论