Update: these instructions don’t apply to WordPress 2.7+. See my newer article for more information.

Ever wonder how to apply special styles to highlight WordPress comments written by the post author or another registered user? Good advice on this point is very rare. Most recommendations are to check against either an email address or a specific user ID. Both of these options are kludges, and both are fragile.

Here’s the right way to do it:

If you want to check whether a comment is by the page author, this is the condition you want to test:

$comment->user_id == $post->post_author

To see whether a comment is by a registered user, check this:

$comment->user_id > 0

I compiled these into a very simple plugin. It has three functions:

  • zb_author_comment() – Returns true if the comment is by the post author. Use it conditionally:

    if ( zb_author_comment() )
    {
        // do author-specific stuff
    }
    
  • zb_user_comment() – Returns true if the comment is by a registered user. Again, use it conditionally:

    if ( zb_user_comment() )
    {
        // do user-specific stuff
    }
    
  • zb_comment_classes() – Outputs user and/or author, if applicable. Useful as CSS classes. For example:

    <div class="comment <?php zb_comment_classes(); ?>">
      ...
    </div>
    

    would output class names that could be styled with the following CSS selectors:

    .comment.user {}
    .comment.author {}
    .comment.author.user {}
    

Enjoy!

If there’s an even slicker way to do either of these checks, I’d love to hear about it – please post in the comments.