The issue is this only works on category archive pages. When viewing individual posts, it doesn’t load the right stylesheet. How can I make this work for both category pages and single post pages that belong to those categories?
quick tip - wrap that code in a function and hook it to wp_enqueue_scripts instead of dumping it in header.php. Makes it cleaner and you can use wp_enqueue_style() properly. also, what happens when posts have multiple categories? You might want to prioritize one over others or you’ll get conflicting styles.
Had this exact issue last year when redesigning a client’s site with category-specific themes. You need to detect categories on both archive and single post pages. Here’s what worked:
The file_exists check stops 404 errors for categories without custom styles. I also threw this into functions.php using wp_enqueue_style instead of direct link tags - better performance and follows WordPress standards. Heads up: if posts have multiple categories, you’ll want to decide which stylesheet loads or find a way to combine them.
Using the category slug is indeed an efficient way to manage styles, but as you’ve noted, handling single posts requires a different approach. You can use get_the_category() to retrieve the categories assigned to the post. If you structure your code to check if you’re on an archive page or a single post, you can ensure that the correct stylesheet is loaded in both instances. It’s also wise to implement a check for the existence of the stylesheet file before including it to prevent any 404 errors. This method provides a robust solution to dynamically load the appropriate styles.