• I am getting to grips with PHP coding and WordPress. So far so good but have been stuck in a rut at the moment and would appreciate any help.

    I am looking to specifically add a new class to each sixth post in the following ‘loop’.

    <?php if (have_posts(is_category('3'))) : query_posts('orderby=title&order=ASC&posts_per_page=-1'); while (have_posts()) : the_post(); ?>
    <div></div>
    <?php endwhile; else: ?>
    <?php endif; ?>

    As it stands, it does a great job of checking if there are any posts and then only bringing up all the posts under a certain category and orders them alphabetically. However I want to add the new class so that every sixth post is targeted with extra lines of CSS to make it fit my design.

    Thanks in advance!

Viewing 2 replies - 1 through 2 (of 2 total)
  • try:

    <?php if (have_posts(is_category('3'))) : query_posts('orderby=title&order=ASC&posts_per_page=-1'); while (have_posts()) : the_post(); ?>
    <div <?php if($wp_query->current_post%6 == 0) echo 'class="new-class"'; ?>></div>
    <?php endwhile; else: ?>
    <?php endif; ?>

    (not tested0

    Thread Starter raybkchan

    (@raybkchan)

    Thanks alchymyth! I tried your code and it sort of worked except I had to make a small change.

    From:
    <div <?php if($wp_query->current_post%6 == 0) echo 'class="new-class"'; ?>></div>

    To:
    <div <?php if($wp_query->current_post%6 == 5) echo 'class="new-class"'; ?>></div>

    When I put in your original code, it added the new class to the first post then every sixth post after that i.e. the 1st, 7th, 13th etc.

    I played around with it and changed the 0 to a 5 it selected the 6th post instead. I’m assuming its because integers (numbers) begin at 0.

    Otherwise, thanks alot for your help! Couldn’t have done it without you!

Viewing 2 replies - 1 through 2 (of 2 total)

The topic ‘Automatically creating a custom CSS class for every sixth post’ is closed to new replies.