WordPress

Highlight Posts In A Certain Category In WordPress

Highlight text 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>
</article>

    <?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.

.highlight{
     background: yellow;
}
Back to top