I use Discourse API client for PHP (by @michaeld I guess) and I can’t find how to get a category name/slug with only with an ID.
I need it to display (slug and id) of all our categories and their sub-categories.
But when I get the categories list, the only information about sub-categories is their id.
michaeld
(Michael - Communiteq)
2017 年7 月 10 日 09:10
2
Thanks, is it implemented in your php client ?
michaeld
(Michael - Communiteq)
2017 年7 月 10 日 10:17
4
No, we never implemented that. Should be fairly easy to do, I can take a look later today.
function getCategoryById($categoryId) {
$datas = $this->_getRequest("/site.json");
$categories = $datas->apiresult->categories;
foreach($categories as $categorie) {
if(($categorie->id) == $categoryId) {
return $categorie;
}
}
riking
(Kane York)
2017 年7 月 14 日 03:14
6
You should probably save the data in a global, so you can call the function multiple times in the same PHP script.
I’d rather use /site.json once (to limit the API’s calls). We’ve added the following function to DiscourseApi.php :
function getSite()
{
return $this->_getRequest("/site.json");
}
and then use it to get wanted informations :
$categories = $discourseApi->getSite()->apiresult->categories;
foreach ($categories as $category) {
if (isset($category->parent_category_id)){
$categories_all[$category->parent_category_id]['subcategory'][$category->id]['id'] = $category->id;
$categories_all[$category->parent_category_id]['subcategory'][$category->id]['slug'] = $category->slug;
$categories_all[$category->parent_category_id]['subcategory'][$category->id]['name'] = $category->name;
} else {
$categories_all[$category->id]['id'] = $category->id;
$categories_all[$category->id]['slug'] = $category->slug;
$categories_all[$category->id]['name'] = $category->name;
}
}
(code from congressus/application/config/discourse.structure.php at master · PartiPirate/congressus · GitHub )
(We don’t use the getCategoryById() I’ve suggested before)
nedbat
(Ned Batchelder)
2020 年3 月 16 日 22:22
8
site.json 似乎是获取所有分类列表的方法。这在 docs.discourse.org 中有提到吗?我一直在查阅文档,寻找获取子分类名称的方法,但没找到。或者有没有更好的方法?
simon
2020 年3 月 17 日 00:14
9
向 site.json 发起 API 请求是获取包含子分类的分类列表的正确方式。此外,如果您希望 site.json 的请求返回私有分类,则需要进行身份验证的 API 请求。
我在文档中没有看到任何关于 site.json 的引用。由于 categories.json 不返回子分类,文档中关于 categories 路由的描述并不准确,它声称该路由返回_所有_分类。我会修正这一点。