2012-02-15 #wordpress

Highlight Posts In A Certain Category In Wordpress

Every website has a main subject, something the website is focused on. For example this site is focused on web development tutorials. As there is a focus point is always better to try to highlight this to your visitors, if you have a Wordpress blog you can easily do this by changing the CSS for posts which fall in this category. Here is a small Wordpress snippet that will check the category of the post and if it's in a certain category it will add a CSS class to the post which you can use to highlight the post. First find out the ID of the category you want to highlight. Within your post loop we need to see if the post is in this category and then add a CSS class to the post. To check the category of a post use the function in_category

if( in_category( $categoryId ) ) {


This function will check to see if the current post is in the category you pass as a parameter, if it is in this category then it will return true. This means we can use it in a if statement to check for the value. To change the class on a post or add a new class we use the Wordpress function post_class(). If we pass a parameter in this function it will add a new class to your post. Here is all the code put together.

while (have_posts()) : the_post(); ?>

if( in_category("20") ) {
     $highlight = "highlight";
} else {
     $highlight = "";
<article <?php post_class($highlight); ?> id="post-<?php the_ID(); ?>">				
      <h1 class="entry-title"><a href="<?php the_permalink(); ?>" rel="bookmark"> <?php the_title(); ?></a></h1>

    <?php endwhile; ?>

Now if you check the output HTML you will see all posts which are part of category ID 20 will have a new CSS class of highlight. All you have to do now is change your CSS file to add a new style for the highlight class.

     background: yellow;


Reliable uptime monitoring and instant alerts for any website downtime.

Get 50% off forever using the code 50OFFUP.