This code snippet enables you to add custom classes to any posts in any archive type loop. In this example, we’ll be adding a custom class to post number 1 and post number 8 on the front page archive.
Demo Video #
Shows how you can add custom classes to different entries based on the number of the post in the loop.
The following snippet adds the classes only if the post number 1 and 8 are present on the 1st page of the paginated archive meaning you’ll need to make sure your posts per page settings for the front page are set to show at least 8 posts.
add_filter( 'post_class', 'filter_post_classes' );
function filter_post_classes( $classes ) {
global $wp_query;
$page = is_paged() ? get_query_var('paged') : 1;
$post_number = $wp_query->current_post;
if ( 0 == $post_number && 1 == $page ) {
$classes[] = 'one';
}
if ( 7 == $post_number && 1 == $page ) {
$classes[] = 'eight';
}
return $classes;
}
Add the code to your front-page.php template or any other template which uses the WordPress Template Hierarchy.
You can also use the code in your child themes functions file and add a conditional tag to the code to target specific archives like this :
add_filter( 'post_class', 'filter_post_classes' );
function filter_post_classes( $classes ) {
if ( ! is_front_page() )
return $classes;
global $wp_query;
$page = is_paged() ? get_query_var('paged') : 1;
$post_number = $wp_query->current_post;
if ( 0 == $post_number && 1 == $page ) {
$classes[] = 'one';
}
if ( 7 == $post_number && 1 == $page ) {
$classes[] = 'eight';
}
return $classes;
}
Swap out the is_front_page
conditional tag to target other archives.
Tested using the Genesis Sample child theme by StudioPress however works in any Genesis or WordPress theme.
Was This Tutorial Helpful?