Add Category Name to REST API

The API responses are designed to only return the IDs. You can then fetch the full information for each term. Of course it would not be very performant to make dozens of requests. So instead, the REST API has the concept of embedding resources.

If you make your request, but include _embed=1 in your URL, WordPress will make those requests for each term for you. So, for example, when fetching a post you’ll see the following response body.

{
  "categories": [
    1
  ],
  "tags": [],
  "_embedded": {
    "wp:term": [
      [
        {
          "id": 1,
          "link": "https:\/\/app.test\/category\/uncategorized\/",
          "name": "Uncategorized",
          "slug": "uncategorized",
          "taxonomy": "category",
        }
      ]
    ]
  }
}

The terms from any taxonomy, including custom taxonomies, will be included in the _embedded[wp:term] array. This’ll work on the custom post type endpoints as well.

Unfortunately, you’ll have to manually iterate through the array to find the embedded term for each ID you have in sub_brand, service_area and location. I’d recommend looping through all the terms first, and building up an object keyed by each term’s ID to have better performance.

const termObjects = {};

for ( const taxonomyTerms of response._embedded[ 'wp:term' ] ) {
    for ( const term of taxonomyTerms ) {
        termObjects[ term.id ] = term;
    }
}

function getTerms( taxonomy, response, termObjects ) {
    const terms = [];

    for ( const termId of response[ taxonomy ] ) {
        terms.push( termObjects[ termId ] );
    }

    return terms;
}

const locations = getTerms( 'location', response, termObjects );