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?

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.