Alternating Comment Classes

This idea expands on something originally done by MooKitty: Comment Backgrounds Hack. Kitty was directly inputting a background in wp-comments.php, but I realized that it made more sense to use an if/else statement and create two classes, comment-even and comment-odd, that could then be styled however the user wished. My end result is like so:

    35  <?php if ($comments) { ?>
    36  <ol id="commentlist">
    37  <?php $i=0; foreach ($comments as $comment) { ?>
    38       <li id="comment-<?php comment_ID() ?>" <?php if($i%2) {echo 'class="comment-even"';} else {echo 'class="comment-odd"';} $i++ ?>>
    39          <?php comment_text() ?>
    40          <p><cite><?php comment_type(); ?> <?php _e("by"); ?> <?php comment_author_l
ink() ?> &#8212; <?php comment_date() ?> @ <a href="#comment-<?php comment_ID() ?>"><?php c
omment_time() ?></a></cite> <?php edit_comment_link(__("Edit This"), ' |'); ?></p>
    41          </li>

Using i=0 as a starting point for the counter allows the logic of if / 2 to work as one expects; the first comment is <li id=”comment-blahdiblah” class=”comment-even”>, etc.

I personally would suggest this as a code change for 1.3+.

[Thanks to Carthik's WordLog for pointing me to MooKitty's hack in the first place.]

7 thoughts on “Alternating Comment Classes

  1. Pingback: wurch.log » Alternierende Kommentarzeilen

  2. My JavaScript version of this only gives you one class – “alternate” is the default – but you can still style the other rows. If you use a selector to get at the parent of the area you want striped, you can set a default, then define the style for the alternate class.

  3. Pingback: The Indiana Jones School of Management

  4. Easier: change the foreach to read foreach ($comments as $num => $comment) then the second line in red to echo 'class="comment-' . ($num%2 ? 'odd' : 'even');

  5. Pingback: Comments with alternating background colors in WordPress at Alex Jones

Leave a Reply

Your email address will not be published. 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>