Adding Custom Class to a Post within The Loop

If you want to add a custom class to the very first post within the loop in WordPress. Simply add the following snippet on your theme’s functions.php file and style them with CSS anyway you want. This snippet could be really helpful to highlight the very first or latest post in different way.

function add_class_to_first_post($classes) {
   global $wp_query;
   if( 0 == $wp_query->current_post )
      $classes[] = 'latest';
      return $classes; }

According to this snippet, we just added “latest” as a custom class on the first post retrieved from the loop. You can change the class with any word you want and style them accordingly. However, there are certain issues that needs to be taken in consideration.

Issue 1: The wrapper or the entry holder (div/article) of the post must have the <?php post_class(); ?> tag added to get it working. It should look something like this:

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

Issue 2: Most probably the index.php and archive.php file would have such tag ( post_class(); ) already added depending on the theme. In that case if you style the custom class with CSS, it would affect the first post on both pages. So make the necessary adjustments based on your own requirement.

In case if you don’t have such template tag ( post_class(); ), simply add it to the wrapper or post holder div. It should work. Hope that helps.

Note: Please keep in mind that the first post would be numbered as 0 and second post as 1. Rest of the loop would follow the same pattern. So, if you want to add custom class to a post displaying third on your website, you would have to change the 0 with 2 within this snippet. I personally tested this snippet on my local server and worked right away without any issues.

Source: WordPress Codex.

Today In History



Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.