Ever wanted to show each comment’s position in a list without using an ordered list (

    ) to do it? Unfortunately, WordPress doesn’t include a function do do this. However, by using a simple PHP trick, we can accomplish this.

    Open comments.php and scroll down to where the comments loop begins:

    <?php foreach ($comments as $comment) : ?>

    Before the loop begins, we need to set the PHP variable we’ll use to determine the number. Change the above line to the following:

    <?php $commentNum = 1; foreach ($comments as $comment) : ?>

    We’ve now assigned the value “1″ to the variable $commentNum.

    Next, find the end of the loop:

    <?php endforeach; ?>

    We need to increase the value of $commentNum by 1 before the loop ends. To do this, we use PHP’s increment operator:

    <?php $commentNum++; endforeach; ?>

    Now you can use the variable $commentNum anywhere within the loop. Simply echo the variable with PHP to display the current comment’s number.

    <?php echo $commentNum; ?>

    Post Revisions:

Stay up to date on WordPress news:

About the author:

Do you have your copy of The WPCandy Quarterly?

The Quarterly is our print magazine all about WordPress. It is released four times yearly (hence the name) and is filled to the brim with exclusive articles about WordPress, written by some of the brightest minds in the community.

Pre-order your issue today!

7 Responses to Weekend QuickTip: Display a Comment’s Number in a List

  1. great tips …

    thanks bro ..

  2. Binny V A says:

    Or use <ol> tag in the html – that would show numbers.

  3. The tag doesn’t offer as many formatting options as one might need. This method allows you to put the number anywhere and inside any HTML element you want.

  4. 500c says:

    I got my dm500c from here

  5. Jonathan says:

    This was what I was looking for, you guys rock!

    J

  6. Jauhari says:

    Is it work on WordPress 2.7?

  7. iov says:

    How to achieve this on twentyten or twentyeleven themes? There isn’t foreach on comments.php?

    Thanks

Leave a Reply

Please note that WPCandy is a moderated community.

 

Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>