I have been working on custom WordPress rest API Endpoint. Goal is to create a WordPress custom route in this route i want to get Category Id and convert it to Category Name. I have written the function but its returning null for the category Id. The function simply get the categories of the WordPress and register the route.How Can I get the all Categories Id and convert category Id into category name.
function w_categories()
{
$categories = get_categories();
$data = [];
$i = 0;
foreach ($categories as $category) {
$data[$i]['id'] = $category->ID;
$i++;
}
return $data;
}
add_action('rest_api_init', function () {
register_rest_route('w/v2', 'trending', [
'methods' => 'GET',
'callback' => 'w_categories',
]);
});
I have been working on custom WordPress rest API Endpoint. Goal is to create a WordPress custom route in this route i want to get Category Id and convert it to Category Name. I have written the function but its returning null for the category Id. The function simply get the categories of the WordPress and register the route.How Can I get the all Categories Id and convert category Id into category name.
function w_categories()
{
$categories = get_categories();
$data = [];
$i = 0;
foreach ($categories as $category) {
$data[$i]['id'] = $category->ID;
$i++;
}
return $data;
}
add_action('rest_api_init', function () {
register_rest_route('w/v2', 'trending', [
'methods' => 'GET',
'callback' => 'w_categories',
]);
});
Share
Improve this question
edited Jun 4, 2020 at 7:06
Jacob Peattie
44.1k10 gold badges50 silver badges64 bronze badges
asked Jun 4, 2020 at 5:47
Shahryar RafiqueShahryar Rafique
1031 bronze badge
2
- You shouldn't need a custom endpoint for this. The built in categories endpoint can be used to get the category name from an ID: developer.wordpress/rest-api/reference/categories/… – Jacob Peattie Commented Jun 4, 2020 at 7:07
- Thanks. @JacobPeattie – Shahryar Rafique Commented Jun 4, 2020 at 7:49
1 Answer
Reset to default 0Instead ID you should use cat_ID
$data[$i]['id'] = $category->cat_ID;
get_categories() return list of category objects with:
"term_id": 7,
"name": "default",
"slug": "default",
"term_group": 0,
"term_taxonomy_id": 7,
"taxonomy": "category",
"description": "",
"parent": 0,
"count": 11,
"filter": "raw",
"cat_ID": 7,
"category_count": 11,
"category_description": "",
"cat_name": "Analiza",
"category_nicename": "default",
"category_parent": 0