Roots Discourse

View Composers for similar categories


I have few categories, each having own page to display posts from that category. I created a View Composer for one of the categories (all good), but I realised that all other categories would have identical View Composers, the only difference being the category name used in the query arguments…

Sorry for dummy question, but what would be the best practice here? Have separate VCs for each category resulting in duplicate code, or get category name from the URL and use it as a parameter? I thought the latter but… not sure :wink:


I wouldn’t get it from the url, but you should be able to reliably get the current category with get_queried_object(). Definitely would not recommend a separate composer for each category.

1 Like

Thanks @alwaysblank!
I also found out in the guide that there could be (although for a different use case) a “base” VC and separate ones which extend() from the base…

PS. as for the category name slug, I meant getting it via $slug = get_post_field( 'post_name', get_post() ); , but you’re right about the other method.

Yes, composers are just classes, so you can do all the normal class stuff with them.