Menu Search
Jump to the content X X
Smashing Conf Barcelona 2016

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

10 Handy WordPress Comments Hacks

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.

You may be interested in the following related posts:

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 Link

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 Link

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 here12.
  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 Link

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 Link

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 Link

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 Link

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 Link

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 Link

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:

(al)

Footnotes Link

  1. 1 https://www.smashingmagazine.com/2009/07/14/5-useful-and-creative-ways-to-use-wordpress-widgets/
  2. 2 https://www.smashingmagazine.com/2009/07/02/power-tips-for-wordpress-template-developers/
  3. 3 https://www.smashingmagazine.com/2009/06/10/10-useful-wordpress-loop-hacks/
  4. 4 https://www.smashingmagazine.com/2009/05/13/10-custom-fields-hacks-for-wordpress/
  5. 5 https://www.smashingmagazine.com/2009/03/04/15-useful-twitter-plugins-and-hacks-for-wordpress/
  6. 6 https://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/
  7. 7 https://www.smashingmagazine.com/2009/05/18/100-amazing-free-wordpress-themes-for-2009/
  8. 8 http://www.wprecipes.com/how-to-add-del-and-spam-buttons-to-your-comments
  9. 9 http://www.wprecipes.com/jamie-asked-how-can-i-display-comments-and-trackbacks-separately
  10. 10 http://www.wprecipes.com/how-to-get-rid-of-links-in-your-comments
  11. 11 http://www.theblog.ca/literal-comments
  12. 12 https://www.smashingmagazine.com/2009/01/08/twitter-avatars-in-comments-wordpress-plugin/
  13. 13 https://www.smashingmagazine.com/2009/01/08/twitter-avatars-in-comments-wordpress-plugin/
  14. 14 http://www.wprecipes.com/ho-to-use-twitter-avatars-in-comments
  15. 15 http://aonach.com/chatter/highlight-author-comments-in-wordpress/
  16. 16 http://www.wprecipes.com/how-to-display-your-average-comments-per-posts
  17. 17 http://www.wprecipes.com/how-to-list-most-recent-comments
  18. 18 http://yoast.com/
  19. 19 http://justintadlock.com/archives/2008/11/01/making-your-themes-comments-compatible-with-wordpress-27-and-earlier-versions
  20. 20 http://www.wprecipes.com/how-to-make-your-comments-template-compatible-with-wordpress-27-and-older-versions
  21. 21 http://www.wprecipes.com/how-to-display-the-most-commented-posts-of-2008
  22. 22 https://www.smashingmagazine.com/2009/07/14/5-useful-and-creative-ways-to-use-wordpress-widgets/
  23. 23 https://www.smashingmagazine.com/2009/07/02/power-tips-for-wordpress-template-developers/
  24. 24 https://www.smashingmagazine.com/2009/06/10/10-useful-wordpress-loop-hacks/
  25. 25 https://www.smashingmagazine.com/2009/05/13/10-custom-fields-hacks-for-wordpress/
  26. 26 https://www.smashingmagazine.com/2009/03/04/15-useful-twitter-plugins-and-hacks-for-wordpress/
  27. 27 https://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/
  28. 28 https://www.smashingmagazine.com/2009/05/18/100-amazing-free-wordpress-themes-for-2009/
SmashingConf Barcelona 2016

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

Advertisement

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 WpRecipes and about blogging on Cats Who Blog . You can stay in touch with Jean by following him on Twitter.

  1. 1

    wow, first comment
    Thanks a lot!

    0
  2. 2

    Just what I needed

    0
  3. 3

    Nice Collection of hacks…. Some of them are quite old.. yet effective. Thanks Jean for putting it all together.

    DKumar M.
    @instantshift

    2
  4. 4

    Nice post – amongst all the wordpress articles available on the net, there isn’t nearly enough attention paid to the comments section.

    A well designed, thought out comment section can really add a nice touch.

    -1
  5. 5

    You should at least mention that #5 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.

    If you know you’re going to be working on 2.7+ it’s just easier to do it that way, and you get a bunch of other classes from comment_class(); that you can also use.

    (SM) Done, thank you!

    2
  6. 6

    yeah thanks i did this before on a Post on some other site can’t remember but it worked on my Blog i had :)

    0
  7. 7

    How about adding a description how to code the “reply” function for old WordPress themes?

    0
  8. 8

    Nice collection.
    Thanks

    0
  9. 9

    Once again some great information that will definitely come in handy…. thanx SM

    1
  10. 10

    Gr8 stuff!!!

    Tnx

    0
  11. 11

    This article makes WordPress closer to me!!

    0
  12. 12

    Such as always, You Smashed us !

    0
  13. 13

    Thanks for the hacks

    1
  14. 14

    Be careful with hack nr. 8.

    Firewalls and packet filters may block http referrers and desktop users do not necessarily have rights to change that.

    A missing http referrer is IMHO not a good indication for spam.

    1
    • 15

      I agree. I used that ‘trick’ and I lost ton of the comments. It killed a lot of non-spam comments. Some of my readers complained…

      2
    • 16

      Some great tips here. Thanks for sharing! :)

      I was just thinking about the safety/reliabilty of the ‘8. Easily Prevent Comment Spam’ tip.
      You answer confirms my concern. Thanks!

      0
  15. 17

    Great thank you! One thing I’d like to add that I think is REALLY important is to allow the commenter a certain amount of time to EDIT or DELETE the comment once it’s been made.

    1
  16. 18

    Nice piece, but I’d just encourage users to consider trying out the Disqus plugin, which takes over the comments system and offers some fabulous modern features such as Facebook and Twitter login, and reblogs from Twitter shown along with the comments. Great stuff.

    0
  17. 19

    I agree with previous comment #14. Additionally, it’s my understanding that checking for referrer in check_comment_flood this way would also block pingbacks and trackbacks, as the same code is used for these.

    0
  18. 20

    Marc Beharry

    July 23, 2009 6:43 am

    Nice, comments are soo underappreciated :)

    0
  19. 21

    Dewey Bushaw

    July 23, 2009 7:20 am

    One thing that I believe comments need is to separate Questions/Answers from Comments. I am getting tired of reading through 50 comments on a tutorial just to find a fix that the author was to lazy to update the post with. Something along the lines of #2 so you would have a tab for Q&A.

    0
  20. 22

    Can anyone tell me how to get rid of the whole “Comment” section as in, not have anything that says how many comments or “No comments”?
    What do I need to delete in my wp code so that it does not appear in certain pages?
    Thanks a lot.

    0

↑ Back to top