nathan12343
Member
Posted 1 year ago #
I want to add a unique and incremental number as the class of
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!
datdesignguy
Member
Posted 1 year ago #
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