admin管理员组文章数量:1336212
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
本文标签: pluginsAdding Custom Endpoint in WordPress Rest API
版权声明:本文标题:plugins - Adding Custom Endpoint in WordPress Rest API 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742376041a2463183.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论