WordPress has lots of great widgets but sometimes they’re just too ordinary. One of our clients recently asked for a small change in recent posts and categories widgets of WordPress and we were happy to execute those changes since it’s the details what makes a website great.
Highlighting the Category of the Current Post
Usually, you find the categories of the posts just under the title of the post and that is also the case in our blog, but if you scroll down on this page, that category information isn’t going to stay on the screen. At the end of the post, if you think that the information you’ve read was useful and want to look for similar posts in the blog you need to scroll up and click the categories under the title. Or you may be showing the categories only in the sidebar area.
If you look at the right-hand sidebar on this page, you’ll see that we have all the categories of our blog are listed there as well. So, in order to make the website a little bit more user-friendly, you can show the categories of the current post in the sidebar area as well. It will be really helpful for visitors who are looking for posts under the same category. A simple CSS highlighting will be enough to solve this problem but we need to tweak WP categories widget a little bit because it doesn’t assign a class to the current category automatically.
So we came up with this code snippet which can be added to your child theme’s functions.php file:
This code basically adds a .current-cat class to the categories if the current post is assigned to that category. And then you can just style it in your css file such as:
.current-cat a{
color: #ff9000; //change the current-cat class links’ color to your theme’s accent color
}
Highlighting the Current Post if it’s in the Recent Posts
The second part of the development was more about a styling concern. We were using two widgets on the sidebar, categories and recent posts. And since categories are highlighted why shouldn’t we do it with the recent posts also?
A small tweak on the recent posts widget helped us to solve that problem.
Warning: This is an addition to the recent posts widget code. You can check out our other posts about the recent post widget with category exclusion to get the full code and make the changes there and add it to your child theme’s functions.php file.
As in the previous example with the categories what this code snippet does is assigning a different class to the current post if it’s in our recent posts list. The classname in our example is .currentpost. So now all you need to do is to highlight this class in your css file.
.currentpost a{
color: #ff9000; //change the .currentpost class links’ color to your theme’s accent color
}
And this was the final result:
We hope you enjoyed this tutorial and apply it in your projects.