[Vuejs]-WordPress API: How do I get the category names by ID in VueJS?

2👍

Since you are unable to edit the endpoint, you’ll need to do an additional API-Request to the /categories endpoint. There are multiple ways to do this.

Request Single Category inside loop

So basically the most obvious thing would it be to loop through all the categories and request the data like this: https://techcrunch.com/wp-json/wp/v2/categories/3457

But obviously, this is not really good for the performance.

Request multiple Categories

In order to reduce it to a single request, you can simply add the ID's comma separated to the query string.

So like this: https://techcrunch.com/wp-json/wp/v2/categories/3457,17396,37621928,576601119

There are plenty of ways to make this happen in code. The easiest one would be to simply loop through your categories and create a flatten array with unique values out of it.

Then you could simply convert the array to comma a seperated string by using JavaScripts join(',') method and create the URL out of it.

In the end, you would need to convert the response Array to an object. In this case, you can simply access categories by ID.

Here’s a working demo:
https://jsfiddle.net/qtejnmym/

I’ve just created this in the browser, feel free to update it to more modern JS

Notice: It seems like TechCrunch will not return every category. You can check this by calling this URL: https://techcrunch.com/wp-json/wp/v2/categories?include=3457,17396,37621928,576601119,449557100,20429,449557102,449557028,424613844,449557096,449557086,15986864,449223024,2401

There are 13 ID's included as query string, but just 10 get returned.

1👍

Looking at your data that’s returned, I noticed that the api is not returning anything other than category ids.

I guessed (and was right) that the endpoint for categories was /categories.

Here’s a sample route to get one of the categories from the site: https://techcrunch.com/wp-json/wp/v2/categories/25515

I don’t recommend looping through the posts and getting the categories one at a time 🙂

You can hit this route instead with a list of ids: https://techcrunch.com/wp-json/wp/v2/categories?include=25515,20429

Parse through the posts and grab a unique list of categories and make a second call.

Here’s a link to the documentation for the categories api for WordPress: http://v2.wp-api.org/reference/categories/

👤Daniel

Leave a comment