WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Loop Statement inside WP Loop (4 posts)

  1. eds-danny
    Member
    Posted 2 years ago #

    Hello to all,

    I need some help with a loop statement. For example we have the base WP Loop and I need another loop inside it to create separate CSS Classes for the first 3 loops. Check the code below:

    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    for ($i=1; $i<13; $i++) {
    echo $i;
    }
    <a class="<?php for ($i=1; $i<4; $i++) { echo $i; } ?>" href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
    <?php endwhile; ?>

    But the code will generate:

    class="123"

    and I need to set only a number per posts, like this:

    class="1" - for Post 1
    class="2" - for Post 2
    class="3" - for Post 3
    and again for the next 3 posts
    class="1" - for Post 4
    class="2" - for Post 5
    class="3" - for Post 6

    Waiting for some help please. Thank you!

  2. alchymyth
    The Sweeper & Moderator
    Posted 2 years ago #

    try:

    for ($i=0; $i<12; $i++) {
    echo $i;
    }
    
    <a class="class-<?php echo $i%3+1; ?>" href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>

    %3 is the modulus operator: http://php.net/manual/en/language.operators.arithmetic.php
    i.e. the remainder of the division ($i divided by 3)

    afaik, css classes should not start with a numeral

  3. esmi
    Forum Moderator
    Posted 2 years ago #

    <?php if (have_posts()) :
    $i = 0;?>
    <?php while (have_posts()) : the_post();
    $i++;
    if( $1 > 3 ) $i = 1;?>
    <a class="<?php echo $i?>" href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a>
    <?php endwhile; endif;?>
  4. eds-danny
    Member
    Posted 2 years ago #

    Thank you very much for your fast replies!

    It works perfect.

Topic Closed

This topic has been closed to new replies.

About this Topic