Category ID as body class

The category name is added to body class-list as in category category-CATEGORY-NAME.

How could I add the category ID as a data attribute, similar to how sidebar category links have; i.e. data-category-id=5

How could I add a similar data attribute for the body for the category page I’m in?

1 Like

Hi Osman :slight_smile:

This should work:

<script type="text/discourse-plugin" version="1.4.0">
    const container = Discourse.__container__;
    const controller = container.lookup('controller:navigation/category');
    
    api.onPageChange((url, title) => {
        let categoryId = controller.get("category.id");
        if(categoryId) {
            document.body.setAttribute('data-category-id', categoryId);
        }
        else {
            document.body.removeAttribute('data-category-id');
        }
    });
</script>
2 Likes

Thanks @Canapin this works perfectly : )

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.