0

I am using the URL: http://website-url.com/wp-json/wp/v2/qd_leadership to get the data for that custom post type. I then created custom taxonomies for this post type. That only displays the taxonomy IDs in the JSON object like so:

"sub_brand": [
  28,
  29,
  30
],
"service_area": [
  31,
  32,
  33
],
"location": [
  34,
  35,
  36
],

Is there a way to add additional information to the wordpress REST API to also add in the taxonomy name along with its ID?

3

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 term of response._embedded[ 'wp:term' ] ) {
    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 );
  • Great answer. Just for the clarity of future readers: .../wp-json/wp/v2/something?_embed=1 – Alvaro Nov 22 '18 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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