• I want to add a unique and incremental number as the class of
    <li> tags in a list. This is so that I can style the li according to it’s position regardless of what the content is. eg:

    <ul>
     <?php  global $post;
                     $myposts = get_posts('category=1&numberposts=3&order=des');
                     foreach($myposts as $post) :
                     setup_postdata($post);?>
            <li class="<?php INSERT_A_NUMBER_HERE_IN_ORDER ?>"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>
                    <?php endforeach; ?>
    </ul>

    So the output will look like:

    <ul>
        <li class="1">Title here</li>
        <li class="2">Title here</li>
        <li class="3">Title here</li>
    </ul>

    I’m sure that it’s not difficult, but not something I have come across.

    Thanks!

Viewing 1 replies (of 1 total)
  • Hi Nathan,

    Here’s a quick and simple way to get the result you want:

    <ul>
     <?php  global $post;
    $cntr = 1;
                     $myposts = get_posts('category=1&numberposts=3&order=des');
                     foreach($myposts as $post) :
                     setup_postdata($post);?>
            <li class="<?php echo "post-" . $cntr; ?>"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>
    <?php $cntr++; ?>
                    <?php endforeach; ?>
    </ul>

    What I’ve done here is add a variable: $cntr with a starting value of 1, and echoed that in the class attribute prefixed with “post-“, so the resulting output in the class attribute becomes “post-N”.

    Just above the call to endforeach; you simply increment the counter like so:$cntr++

    Hope that helps! 🙂

    – Greg

Viewing 1 replies (of 1 total)

The topic ‘Inserting a sequential class in the loop’ is closed to new replies.