Monday, May 17th, 2010

Custom Comments HTML Output

If you like it, say thanks by sharing it

Displaying all the comments on a Post is incredibly easy. In your single.php file you probably have a line like this:

<?php comments_template(); ?>

That line basically calls/includes your comments.php file. Within that, the line to output all comments is something really simple like this:

<ol class="commentlist"> <?php wp_list_comments(); ?> </ol>

But that doesn’t leave much by way of customizing the HTML that gets output, does it? Fortunately it’s fairly easy to specify your own formatting in a non-destructive non-core-altering way. Although personally, I’m having one little issue with it. Let’s take a look.

Why would you need this?

This is what you get as the defacto standard comment output:


This is from the new 2010 theme slated to come out with WordPress 3

But what if you wanted something more like this?


From a new client site I’ve been working on

The best way to get into that new skin is to get your hands on the HTML, as CSS alone isn’t quite going to get us there.

Custom output through a callback function

The trick is is that the wp_list_comments function accepts a parameter for a callback function. This function overrides what the output of each comment will be. Here is an example of that:

<ol class="commentlist"> <?php wp_list_comments('type=comment&callback=format_comment'); ?> </ol>

The above code will only output “comments” (and not trackbacks or pingbacks) and will call a custom function “format_comment” for formatting the comment. This function needs to be built in your functions.php file, and better be present before you call this function otherwise you’ll throw an error.

The callback function is completely in charge of the comment formatting. It could be something completely whacky like this:

<?php function format_comment() {  ?> <li>This is whack, yo.</li> <?php } ?>

Which would return that ridiculous sentence for every single comment, instead of the actual comment. Of course you wouldn’t (probably) ever do that. What you probably want to do, is just adjust how the different standard comment-related data is output. To do that, first you pull in the comment globals, then you can use all the comment functions that return the stuff that you probably want:

  • get_comment_link
  • get_comment_author
  • get_comment_date
  • get_comment_time
  • get_comment_text
  • etc.

Here is a customized formatting function I recently used:

<?php



Continue Learning...

If you like it, say thanks by sharing it

Category: Graphics
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
  • *