Get a term object using getEntityRecords

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?

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

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.com/wp-json/wp/v2) to see all the registered routes and endpoints, and the parameters for each endpoint.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x