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

rest api - Get a term object using getEntityRecords

programmeradmin0浏览0评论

Given a term ID, how can I fetch the term object by its ID using getEntityRecords?

I have a custom taxonomy with the slug genre.

getEntityRecords( 'taxonomy', 'genre' );

Currently this retrieves all terms under genre, but I'd like to retrieve the term which matches ID. Can I pass the taxonomy ID somewhere in the above function?

Given a term ID, how can I fetch the term object by its ID using getEntityRecords?

I have a custom taxonomy with the slug genre.

getEntityRecords( 'taxonomy', 'genre' );

Currently this retrieves all terms under genre, but I'd like to retrieve the term which matches ID. Can I pass the taxonomy ID somewhere in the above function?

Share Improve this question asked Mar 3, 2021 at 14:05 Siddharth ThevarilSiddharth Thevaril 5676 silver badges22 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

So getEntityRecords( 'taxonomy', 'genre' ) will make a request to the "list terms" endpoint at /wp/v2/genre (or /wp/v2/<rest_base> if your taxonomy uses a custom rest_base) in the REST API, and because the "list terms" endpoint for custom taxonomies by default use the same parameters used by /wp/v2/categories (the "list terms" endpoint for the built-in category taxonomy), if you want to limit the result set to specific term IDs, then you can use the include parameter like so:

const termId = 123;

// The optional third parameter is an object which contains arguments for the
// specific REST API endpoint. On successful requests, this will be an array of
// term objects.
const terms = getEntityRecords( 'taxonomy', 'genre', { include: [ termId ] } );

console.log( terms && terms[0] ? terms[0].name : terms );

But instead of using getEntityRecords(), you might want to just use getEntityRecord() to get a single term object/data:

const termId = 123;

// The third parameter is mandatory and it is the term ID.
const term = getEntityRecord( 'taxonomy', 'genre', termId );

console.log( term?.name );

And if you don't already know, you can make a request to /wp/v2 (e.g. https://example/wp-json/wp/v2) to see all the registered routes and endpoints, and the parameters for each endpoint.

发布评论

评论列表(0)

  1. 暂无评论