WordPress.org

Support

Support » Plugins and Hacks » [Resolved] Loop Statement inside WP Loop

[Resolved] Loop Statement inside WP Loop

  • 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!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Michael

    @alchymyth

    Forum Moderator

    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

    esmi

    @esmi

    Forum Moderator

    <?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;?>

    Thank you very much for your fast replies!

    It works perfect.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘[Resolved] Loop Statement inside WP Loop’ is closed to new replies.