10 Handy WordPress Comments Hacks

About The Author

This guest post was written by Jean-Baptiste Jung, a 28-year-old blogger from Belgium, who blogs about Web Development on Cats Who Code, about WordPress at … More about Jean-Baptiste ↬

Email Newsletter

Weekly tips on front-end & UX.
Trusted by 200,000+ folks.

Comments sections are neglected on many blogs. That is definitely a bad thing, because comments represent interaction between you and your readers. In this article, we’ll have a look at 10 great tips and hacks to enhance your blog’s comments section and give it the quality it deserves.

Comments sections are neglected on many blogs. That is definitely a bad thing, because comments represent interaction between you and your readers. In this article, we’ll have a look at 10 great tips and hacks to enhance your blog’s comments section and give it the quality it deserves.

Screenshot

The problem. Whether or not you allow readers to add comments without having to be approved, you will often need to edit, delete or mark certain comments as spam. By default, WordPress shows the “Edit” link on comments (using the edit_comment_link() function) but not “Delete” or “Spam” links. Let’s add them.

The solution. First, we have to create a function. Paste the code below in your functions.php file:

function delete_comment_link($id) {
  if (current_user_can('edit_post')) {
    echo '| <a href="'.admin_url("comment.php?action=cdc&c=$id").'">del</a> ';
    echo '| <a href="'.admin_url("comment.php?action=cdc&dt=spam&c=$id").'">spam</a>';
  }
}

Once you have saved functions.php, open up your comments.php file, and add the following code where you want the “Delete” and “Spam” links to appear. They must go in the comment loop. In most themes, you’ll find an edit_comment_link() declaration. Add the code in just after that.

delete_comment_link(get_comment_ID());

Code explanation. The first thing we did, of course, was to make sure the current user has permission to edit comments. If so, links to delete and mark a comment as spam are displayed. Note the use of the admin_url() function, which allows you to retrieve your blog admin’s URL.

Source:

2. Separate TrackBacks From Comments

Screenshot

The problem. Do your posts have a lot of TrackBacks? Mine do. Trackbacks are cool because they allow your readers to see which articles from other blogs relate to yours. But the more TrackBacks you have, the harder the discussion is to follow. Separating comments from TrackBacks, then, is definitely something to consider, especially if you do not use the “Reply” capabilities introduced in WordPress 2.7.

The solution. Open and edit the comments.php file in your theme. Find the comment loop, which looks like the following:

foreach ($comments as $comment) : ?>
    // Comments are displayed here
endforeach;

Once you have that, replace it with the code below:

<ul class="commentlist">
    <?php //Displays comments only foreach ($comments as $comment) : ?>
        <?php $comment_type = get_comment_type(); ?>
        <?php if($comment_type == 'comment') { ?>
      <li>//Comment code goes here</li>
  <?php }
    endforeach;
</ul>

<ul>
    <?php //Displays trackbacks only foreach ($comments as $comment) : ?>
        <?php $comment_type = get_comment_type(); ?>
        <?php if($comment_type != 'comment') { ?>
      <li><?php comment_author_link() ?></li>
  <?php }
    endforeach;

</ul>

Code explanation. Nothing hard about this code. The get_comment_type() function tells you if something is a regular comment or a TrackBack. We simply have to create two HTML lists, filling the first with regular comments and the second with TrackBacks.

Source:

Screenshot

The problem. Bloggers are always looking to promote their blogs, and spammers are everywhere. One thing that totally annoys me on my blogs is the incredible amount of links left in comments, which are usually irrelevant. By default, WordPress transforms URLs in comments to links. Thankfully, if you’re as tired of comment links as I am, this can be overwritten.

The solution. Simply open your function.php file and paste in this code:

function plc_comment_post( $incoming_comment ) {
  $incoming_comment['comment_content'] = htmlspecialchars($incoming_comment['comment_content']);
  $incoming_comment['comment_content'] = str_replace( "'", '&apos;', $incoming_comment['comment_content'] );
  return( $incoming_comment );
}

function plc_comment_display( $comment_to_display ) {
  $comment_to_display = str_replace( '&apos;', "'", $comment_to_display );
  return $comment_to_display;
}

add_filter('preprocess_comment', 'plc_comment_post', ’, 1);
add_filter('comment_text', 'plc_comment_display', ’, 1);
add_filter('comment_text_rss', 'plc_comment_display', ’, 1);
add_filter('comment_excerpt', 'plc_comment_display', ’, 1);

Once you have saved the file, say goodbye to links and other undesirable HTML in your comments.

Code explanation. The first thing we did was create two functions that replace HTML characters with HTML entities. Then, using the powerful add_filter() WordPress function, we hooked the standard WordPress comments processing functions to the two functions we just created. This makes sure that any comments added will have their HTML filtered out.

Sources:

4. Use Twitter Avatars In Comments

Screenshot

The problem. Bloggers find Twitter very useful because it allows them to promote their blog and stay connected to other bloggers and their own audience. Because of Twitter’s popularity, why not illustrate comments with Twitter avatars instead of the normal gravatars?

The solution.

  1. The first thing to do is get the functions file here.
  2. Once you have that, unzip the archive to your hard drive, and then open the twittar.php file.
  3. Select all of its content and paste it to your blog’s functions.php file.
  4. The last thing to do is open your comments.php file and find the comments loop.
  5. Paste the following line in the comments loop:

    <?php twittar('45', 'default.png', '#e9e9e9', 'twitavatars', 1, 'G'); ?>
    

Code explanation. Some months ago here at Smashing Magazine, an awesome plug-in named Twittar was released. Its purpose is to allow you to use Twitter avatars on your WordPress blog. Because of the number of requests I received from WpRecipes.com readers, I decided to turn the plug-in into a hack, for people who prefer hacks to plug-ins.

Of course, you could simply install the plug-in rather than insert its content into your function.php file. It’s up to you.

Sources:

5. Set Apart Author Comments With Style

Screenshot

The problem. For blog posts that have a lot of comments, finding the author’s comments and responses to reader questions is not always easy, especially if the blog don’t have WordPress 2.7’s threaded comments feature. Happily, it is possible to give author comments a different style so that readers can always quickly find your answers.

The solution.

  1. Open the comments.php file and find the comment loop:

    <?php foreach comment as $comment) { ?>
    
  2. After that line, paste in the following:

    <?php
    $isByAuthor = false;
    if($comment->comment_author_email == get_the_author_email()) {
    $isByAuthor = true;
    }
    ?>
    
  3. Once that’s done, find the line of code that represents comments (it may vary depending on your theme):

    <li class="<?php echo $oddcomment; ?>" id="comment-<?php comment_ID() ?>">
    
  4. Now we have to output the authorcomment class if the comment was made by the author:

    <li class="<?php echo $oddcomment; ?> <?php if($isByAuthor ) {
     echo 'authorcomment';} ?>" id="comment-<?php comment_ID() ?>">
    
  5. The last thing we do is create a CSS class for author comments. Open the style.css file and insert the code. Replace the example colors with your colors of choice.

    .authorcomment{
      color:#fff;
      font-weight:bold;
      background:#068;
    }
    

Code explanation. Basically, this code compares each email address left by a commentator to the author’s email address. If they match, the $isByAuthor is set to true. When comments are displayed on screen, the value of $isByAuthor is checked. If it returns true, then the authorcomment class is added to the container.

It can be done more easily on Wordpress 2.7+ by just adding comment_class(); to the comment’s DIV, which automatically adds the class bypostauthor when you’re commenting on your own post (Thanks, Nima!).

Source:

6. Display Total Number Of Comments And Average Number Of Comments Per Post

Screenshot

The problem. On your blog’s dashboard, WordPress tells you how many total comments your blog has received. Unfortunately, there’s no function for displaying this information publicly. Displaying the total number of comments on your blog and average number of comments per post can be very helpful, especially if you have a page for advertising opportunities.

The solution.

<?php
$count_posts = wp_count_posts();
$posts = $count_posts->publish;

$count_comments = get_comment_count();
$comments  = $count_comments['approved'];

echo "There's a total of ".$comments." comments on my blog, with an average ".round($comments/$posts)." comments per post.";
?>

Code explanation. Introduced in version 2.5, the wp_count_posts() and get_comment_count() functions allow you to easily retrieve the total number of posts and comments, respectively, on your WordPress blog. To derive the average number of comments per post, we have to do a bit of simple math, using the PHP round() function to make sure we end up with an integer.

Source:

7. Display X Number Of Most Recent Comments

Screenshot

The problem. By default, WordPress provides a widget that outputs a list of however many of the most recent comments. This is great, but sometimes you want this functionality without a widget.

The solution. This hack is very simple: just paste this code wherever you need a certain number of the most recent comments to be displayed. Don’t forget to specify the actual number on line 3 (after the LIMIT SQL clause).

<?php
  $pre_HTML ="";
  $post_HTML ="";
  global $wpdb;
  $sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type,comment_author_url, SUBSTRING(comment_content,1,30) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) WHERE comment_approved = '1' AND comment_type = ’ AND post_password = ’ ORDER BY comment_date_gmt DESC LIMIT 10";

  $comments = $wpdb->get_results($sql);
  $output = $pre_HTML;
  $output .= "n<ul>";
  foreach ($comments as $comment) {
    $output .= "n<li>".strip_tags($comment->comment_author) .":" . "<a href="" . get_permalink($comment->ID)."#comment-" . $comment->comment_ID . "" title="on ".$comment->post_title . "">" . strip_tags($comment->com_excerpt)."</a></li>";
  }
  $output .= "n</ul>";
  $output .= $post_HTML;
  echo $output;
?>

Code explanation. As in the last hack, we use the $wpdb object here, too, this time with the get_results() method. Once the comments have been retrieved by the WordPress database, we simply use a for loop to concatenate the comments into an HTML unordered list. The $pre_HTML and $post_HTML variables, initialized at the top of this code, allow you to define which content should go before and after the comments list.

Sources:

8. Easily Prevent Comment Spam

Screenshot

The problem. Comment spam is such a pain for everyone. Akismet is a good solution, but why not block spammers outright instead of just marking their comments as suspected spam? This code looks for the HTTP referrer (the page where the request comes from) and automatically blocks the comment if the referrer is incorrect or not defined.

The solution. Paste the following code in your functions.php file:

function check_referrer() {
    if (!isset($_SERVER['HTTP_REFERER']) || $_SERVER['HTTP_REFERER'] == “”) {
        wp_die( __('Please enable referrers in your browser, or, if you're a spammer, bugger off!') );
    }
}

add_action('check_comment_flood', 'check_referrer');

That’s all. Once you’ve saved the file, your blog will have a new level of protection against spam.

Code explanation. This code automatically rejects any request for comment posting coming from a browser (or, more commonly, a bot) that has no referrer in the request. Checking is done with the PHP $_SERVER[] array. If the referrer is not defined or is incorrect, the wp_die function is called and the script stops its execution.

This function is hooked to WordPress’ check_comment_flood() function. This way, we can be sure that our check_referrer() function is called each time a comment is posted.

Source:

9. Keep WordPress Backwards Compatible With Versions Older Than 2.7

Screenshot

The problem. Released some months ago, WordPress 2.7 introduced a totally new commenting system, allowing you to thread comments and display them on separate pages. Although this is great, keep in mind if you are creating a theme for a client or for online distribution that many users still haven’t upgraded their installation to version 2.8 or even 2.7. This code allows 2.7+ users to benefit from the new commenting system, while keeping the old system functional for people with older versions.

The solution. You’ll need two files for this recipe: the first is a WordPress 2.7 compatible comments file called comments.php. The second is a comment template for older WordPress versions called legacy.comments.php. Both of these files go in your theme directory.

Paste this code in your functions.php file.

<?php
add_filter('comments_template', 'legacy_comments');

function legacy_comments($file) {
  if(!function_exists('wp_list_comments')) : // WP 2.7-only check
    $file = TEMPLATEPATH.'/legacy.comments.php';
  endif;
  return $file;
}
?>

Code explanation. This code creates a function called legacy_comments(), which is hooked to WordPress comments_template function. Each time WordPress calls comments_template(), our legacy_comments() function is executed. If the wp_list_comments() function doesn’t exist, the code automatically loads legacy.comments.php instead of comments.php.

Sources:

10. Display Most Commented Posts From A Certain Period

Screenshot

The problem. Number of comments is a good way to measure a blog post’s popularity and is a good filter for displaying a list of your most popular posts. Another great idea is to restrict a list of your most popular posts to a particular period, like “Last month’s most popular posts,” for example.

The solution. Simply paste the following code where you’d like your most commented posts to be displayed. Don’t forget to change the dates values on line 3 according to your needs.

<ul>
<?php
$result = $wpdb->get_results("SELECT comment_count,ID,post_title, post_date FROM $wpdb->posts WHERE post_date BETWEEN '2009-06-01' AND '2009-07-01' ORDER BY comment_count DESC LIMIT 0 , 10");

foreach ($result as $topten) {
    $postid = $topten->ID;
    $title = $topten->post_title;
    $commentcount = $topten->comment_count;
    if ($commentcount != 0) {
    ?>
         <li><a href="<?php echo get_permalink($postid); ?>"><?php echo $title ?></a></li>
    <?php }
}
?>
</ul>

Code explanation. The first thing we did was send out an SQL query to the WordPress database using the $wpdb object. Once we got the results, we used a simple PHP foreach statement to display the most popular posts from a certain period in an HTML unordered list.

Source:

You may be interested in the following related posts:

Smashing Editorial (al)