Hey guys im trying to add a class every 4 post in wordpress loop like in the image above

enter image description here

im using the simple loop of wordpress, I have investigated about using a counter or modulo but have not found a solution, can you guys help me, Thanks.

 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<div class="col-md-3">

    <div class="box_ow">
            <div class="rollover_cont" style="background-color: #098EAD; mix-blend-mode: multiply; z-index:1;">
            <h3> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h3>
            <a class="go_project_link" href="<?php the_permalink(); ?>">Go to Project ></a>
            <img class="img-fluid icons_social_img" src="<?php bloginfo('template_directory') ?>/assets/images/icons_social.svg" alt="">


            <img class="img-fluid" src="<?php bloginfo('template_directory') ?>/assets/images/image_holder.jpg" alt="">


<?php endwhile; else : ?>
    <p><?php esc_html_e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

1 Answer 1


You can try something like this:

if ( have_posts() ) : 
    // define count var ##
    $count = 1; 

    while ( have_posts() ) : 


        <div class="class_bg_<?php echo $count; ?>">XXX</div>

    // iterate ##
    $count ++;

    // reset count if reached 5 ##
    if( 5 == $count ){ $count = 1; }


  • 1
    Genius!!, don´t know how I could not think it like that, thank you very much my friend!!! Nov 19, 2020 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.