Return WordPress REST API With Categories Name

Jan 22, 2024


When you see the JSON of WordPress REST API, Categories has an array with the category ID. To fetch the Category Name you have to have one more query using Category ID to get name of the Category.

To save one more query in our app, we can directly return the Category name in WordPress REST API.

So, you get these types of objects, see the “categories” and “tags” keys below.

{
    "id": 240,
    "date": "2024-01-19T17:30:35",
    "date_gmt": "2024-01-19T17:30:35",
    "guid": {
        "rendered": "https://api.example.com/?p=240"
    },
    "modified": "2024-01-20T04:24:29",
    "modified_gmt": "2024-01-20T04:24:29",
    "slug": "test-post",
    "status": "publish",
    "type": "post",
    "link": "https://api.example.com/test-post/",
    "title": {
        "rendered": "You Gonna Be Rich This Year 2024"
    },
    "content": {
        "rendered": "\n<pre class=\"wp-block-code\"><code>function Hello(){\n   const beckkk = 12;\n   return beckkk;\n}</code></pre>\n\n\n\n<p>I’ll make money through blogging this year 2024</p>\n",
        "protected": false
    },
    "excerpt": {
        "rendered": "<p>I’ll This is a test post</p>\n",
        "protected": false
    },
    "author": 1,
    "featured_media": 0,
    "comment_status": "open",
    "ping_status": "open",
    "sticky": false,
    "template": "",
    "format": "standard",
    "meta": {
        "cybocfi_hide_featured_image": "",
        "footnotes": ""
    },
    "categories": [
        14,
        17
    ],
    "tags": [
        3,
        5
    ]
}

As you can see you get the categories with ID.

To return the Categories Name in WordPress REST API follow these steps.

  1. Open your WordPress Theme on Code Editor
  2. Go to functions.php
  3. Add these codes in function.php

Here is the code, add this code below in your function.php

function prepare_rest($data, $post, $request){
	$_data = $data->data;
	
	$cats = get_the_category($post->ID);
	$_data['cats'] = $cats;
	$data->data = $_data;
	
	return $data;
}
add_filter('rest_prepare_post', 'prepare_rest', 10,3);

After updating you can see the changes in your JSON API something like this.

"cats": [
    {
        "term_id": 14,
        "name": "Python",
        "slug": "python",
        "term_group": 0,
        "term_taxonomy_id": 14,
        "taxonomy": "category",
        "description": "",
        "parent": 0,
        "count": 2,
        "filter": "raw",
        "cat_ID": 14,
        "category_count": 2,
        "category_description": "",
        "cat_name": "Python",
        "category_nicename": "python",
        "category_parent": 0
    }
],

Conclusion

Adding that simple code in functions.php will save one query. Now you can directly map through categories name.