Automatically Highlight Admin Comments in WordPress

Automatically Highlight Admin Comments in WordPress

We’re always on the lookout for new and better ways of improving old work. Today’s post will revisit “Unique Author Comment Styles in WordPress“, a tutorial from last April that showed how to style the comments from a post’s author differently.

In this follow up, we’re going to do better. The basis for this upgrade falls on a messy PHP “if…else” statement that was present in the old method. Below, we’ll explore two different methods for updating your blog’s admin highlighting system.

The Manual Array Method

This time around, we’re going to make it easy for ourselves to add in additional administrators without much additional code. Instead of using a bloated OR check for each email address, we’ll just have WordPress run through a preset array containing all of the emails of blog administrators. If the email of a commenter also belongs to an administrator, the comment will be assigned a separate style to make it stand out.

Build the Email Array

Before we’re able to have comments highlighted, we’ll need to specify which emails deserve special treatment. I’ve used some of Sam and I’s email addresses as an example.

You’ve Got Options

Emails do not have to belong to a registered user in this method. If you have multiple email accounts, the array can check for all of them. This opens up many more options for expansion.

The downside to this route is the loss of automation. Each email addresses must be entered in manually by the blog administrator. It would be much easier to have WordPress automatically detect the administrator accounts for the blog installation. That’s where the second option comes in.

The Automated Database Method

If we wanted to, we can code this so that we’ll never have to manually insert emails into the comments.php file once it’s been set up. We can have WordPress pull all of the email addresses of registered users with privileges of Editor and Administrator. For most blogs, this will fit your needs just fine.

Query the Database

We’ll first need to get all of the admin emails from the database and place them into an array. This is easy to do using the WordPress database object, to query the database for specific users.

If this is your first experience with the WordPress database object (or databases in general) the code above may seem a little bit confusing. Here’s a breakdown of what’s going on to help sort it out:

  1. The $user_level variable contains a number 1-10. WordPress user roles (e.g. Administrator, Editor, etc.) are all represented by a number value. To select Administrator accounts only, this number must be set to 8.
  2. The $admin_emails array will hold the emails returned from the query.
  3. The first database query searches the usermeta table for all users with a user level greater than or equal to the one stored in $user_level. The results are stored in the $admin_accounts array.
  4. Each item in the $admin_accounts array is processed, and the user table is queried using the user id number pulled from step 3. The email address is retrieved and stored in the $admin_emails array using the user id as an identifier in the array.

By the end of this code block, we have an array containing the email addresses of the specified user levels stored in $admin_emails. The nice part? This method will update itself when new users are registered. Just set it and forget it.

Marking Administrator Comments

At this point, both methods have the same next step. You’ll have an array of administrator emails stored in $admin_emails. We’ll need this as a reference when marking comments for special attention.

Filter the Comments

Now that we’ve got a list, we need to check each comment for admin email matches. If one is found, the comment will be assigned a class of “admincomment” and get different styling.

In the comments.php file of your blog theme, locate the foreach comment loop, and paste the following immediately under the start of it:

The above code grabs the comment author’s email address and checks it against those in the admin email array. If a match is found, $admin_comment is set to true.

Assign Special Class to Comments

Special comments are marked with a class of  “admincomment” by default. I’ve put a stripped down sample comment below to help you visualize. Pay special attention to the PHP included in the class attribute.

Remember that the comment structure must be after the $isByAdmin loop in the previous step in order to work.

Admin Comment in Action

Styling the Comments

Giving administrator comments some extra flair is the easy part. In both methods above, you’ll end up with a class of “admincomment” on comments to highlight. Since you’ve got a specific class to target, giving it some special styling is just an extra CSS style away.

I’ve included a sample CSS snippet below to help you get started, but feel free to get creative on your final product.

Download Code Snippets

To help you along, I’ve put together a comment file with the necessary code snippets. It should help clear up any confusion left over about placement and ordering. You can grab the file using the link in the sidebar.

Available Soon in Plugin Form

Not into the idea of building it yourself? Lucky for you, we’ve almost finished translating this into an easy to use class for WordPress theme development.

The plugin version contains the methods shown above, as well as a few other useful ones not shown here. We’re planning to have it available for download in a few days. It will be the first project launch since Supersized.

Have any special feature requests? Leave them in the comments below and we’ll be sure to consider including them before making the final release.

Posted Thursday, September 3rd, 2009 · Back to Top


Add Comment

46 Comments 14 Mentions

  1. gavin Steele Author Editor

    This is great, and a WordPress plugin is a great idea! Would be cool if the css could add a little diagonal banner across the photo saying “admin”. I guess thats just a css thing though.


  2. Eric B. Author Editor

    This is a very useful guide! I’ve bookmarked it to follow when I design my next WordPress theme.
    .-= Eric B.´s last blog ..Using Whitespace For a Better Design =-.


  3. Jim Hutchinson Author Editor

    This is a bit different than just highlighting the author comments, for which there are several plugins. In this one, the commenter must be an admin. That makes it stand out more. Nice.
    .-= Jim Hutchinson´s last blog ..Create a WordPress Theme in 8 Minutes =-.


  4. Joël Cox Author Editor

    Great follow up! *bookmark*

    Funny to see my comment in the example picture.
    .-= Joël Cox´s last blog ..Review: De wet op internet =-.


  5. Mike More Author Editor

    Now, what about having a CSS class for each user role -not just admins- so every commenter with different role will have the suitable style..?


    • Zach Dunn Author Editor


      If you checked the user_level on each commenter, you could make a switch statement to handle multiple roles. That’s actually one of the features in the plugin we’re releasing shortly, so you may want to check back.


  6. Mike More Author Editor

    Alright , I’ll wait for the plugin.. :)

    Small Q.: Can’t I subscribe somewhere here to get the comments emailed to me?
    .-= Mike More´s last blog ..@Google: you got Pages, Sites and Blogspot… why?! =-.


    • Zach Dunn Author Editor


      You’ve stumbled on an upcoming “To Do” list item for this blog’s theme.


  7. Ryan Rampersad Author Editor

    I’ve always loved the highlighted author comments, I always look at them, otherwise I glance at the rest. Thanks for the tips.
    .-= Ryan Rampersad´s last blog ..Save The Developers is Back, Sort Of =-.


  8. reza Author Editor

    hi zach

    cant we just change css style of comment-author-admin class or authorcomment class?

    those are classes for admin comments in wp
    .-= reza´s last blog ..Dynamic_slider_Green =-.


  9. NotAlame Author Editor

    How can I use the #     $admin_accounts = $wpdb->get_results("SELECT * FROM $wpdb->usermeta WHERE meta_key = 'wp_user_level' AND meta_value >= $user_level ");
    to display the user level??


  10. jen Author Editor

    Very nice. I’m taking a crack at my first WP theme. Will try to work this in. Thanks.
    .-= jen´s last blog ..Session Timeout Warning PHP Example with jQuery/JS =-.


  11. Joseph Author Editor

    Great timing…just finished a client site and was thinking, “It would be cool to highlight the author’s comments in the comment thread”. Thanks!
    .-= Joseph´s last blog ..Textmate WordPress Bundle Released (version 0.5) =-.


  12. Max Author Editor

    I am a little bit confused about where to put the first two codes (manual and automatic)? where to insert them? in what file? Where should I make a query? should I create a new file?

    Thanks for a quick answer!

    With best wishes,


    • Zach Dunn Author Editor


      The Manual and Automatic methods can both be placed inside the comments.php file, directly under the line that checks for “if comments”. Hopefully that helps!


  13. Chris Cook Author Editor

    Is a plugin ready? I love the CSS for your comments in the images you used. Very nice.
    .-= Chris Cook´s last blog ..Detecting iPhone visitors with PHP =-.


  14. Jad Graphics Author Editor

    Thank you very much. Although, I think I will be waiting for the plugin.


  15. PSD to HTML Author Editor

    Just wanted to drop a line and say thank you very much for this.

    I was doing a psd to wordpress port and the client wanted the user comments to display to the right and uthor comments to the left.

    This worked flawlessly. Keep up the great work!

    Greatly appreciated.
    .-= PSD to HTML´s last blog ..Ecliptic Rift » Blog Archive » Current WordPress plugins =-.


  16. Keyston Author Editor

    an easier way is to use the following code



  17. John Author Editor

    The only ‘foreach’ loop I see in comments.php is in the code you gave me here, from “The Automated Database Method”. Before I pasted that into comments.php, there were no occurances of foreach in that file.
    .-= John´s last blog ..Evasive Maneuvers =-.


  18. tiki god Author Editor

    there is no loop in the wordpress comments file anymore, I have all my custom comment stuff in the functions.php file, and the automatic way is not working from there.

    any suggestions? I’ve been able to get the manual method to work, but I’m getting “illegal function” errors when I try putting the automatic code into the functions.php file.


    • Zach Dunn Author Editor

      @tiki god

      I’m a little confused as to why you have your comment handling inside the functions.php file.

      If newer versions of themes do not have the comment loop inside single.php, then it is typically located within the comments.php template file.


  19. tiki god Author Editor

    WordPress no longer has the loop in either the single.php file nor in the comments.php file. it’s a part of the core files now and if you want to change it you have to put it all in your theme’s functions.php

    most themes that fully support the new comments system will only show : ” wp_list_comments();” in the comments.php file.

    that’s otto’s blog, but I remember the official 2.7 release announcement mentioned it too.


  20. CT Author Editor

    Thank you very much. Although, I think I will be waiting for the plugin.


  21. Mike Little Author Editor

    As reza points out above WordPress already adds three classes to each comment (using the standard wp_list_comments() function).
    If the commenter is a user it adds
    byuser and
    and if the commenter is also the post auther it adds
    Those can be used to style comments from ‘known’ commenters.

    So, the only use your first code example gives is to highlight a registered user commenting with an alternative email which won’t even be displayed. Why would they do that? Doesn’t make sense to me.

    Your second example is rather out of date. Numeric user levels are irrelevant now. You should be checking roles and/or capabilities.
    And the whole lot should be hooked to the ‘comment_class’ filter in your functions.php

    Try this:

    add_filter('comment_class', 'add_author_role', 10, 4); function add_author_role($classes, $class, $comment_id, $post_id) { $comment = get_comment($comment_id); if ( $comment->user_id > 0 && $user = get_userdata($comment->user_id) ) {        $classes[] =  join(' author-role-', array_merge(array(''), array_keys($user->wp_capabilities)));    }    return $classes;}


    • Zach Dunn Author Editor

      @Mike Little

      Thanks so much for taking the time to provide the update! I’ll admit I haven’t stayed as current as I should over the past two major releases of WordPress, and this is great motivator to get back up to speed.


  22. Tech Maish Author Editor

    Thank you so much for this useful article. Now it is easy to highlight admin comments in wordpress blog. This post is very helpful.


  23. Jean-Paul Horn Author Editor

    Thanks Mike! That block of code was *just* what I needed in an effort to trim down our css for a multi-user blog!


  24. ahmed Author Editor


    My site

    please tell me how can i highlight admin comment



  25. Jason Author Editor

    Ahmed, looks like you just need to use the class of ‘comment-author-admin’ and put specific styles on that.


  26. Barnevern Author Editor

    Well documented and simple. A special gravatar or comment logo could do the same job, but styling the admins comment is a good tips.

    Thanks for sharing, it is just what I was looking for!


  27. ExampleMag Author Editor

    Highlighting admin comments will be quite helpful for my site.
    Thanks for sharing!


  28. NnpctO Author Editor

    Почему у меня не получается проделать это??? В чем может быть дело? Я уже все просмотрел и не могу найти ошибку. Что я делаю не так? Мне тоже хочется воспользоваться такой функцией. Может попробовать для начала обновить WordPress? Мне, конечно, не хотелось бы обновлять, потому что мне его оптимизировали. Пришлите, пожалуйста, рекомендации на мою почту. Заранее большое вам спасибо!


  29. NnpctO Author Editor

    Why at me it is impossible to do it??? In what there can be a business? I already have seen all and I can not find an error. What do I do not so? I too would like to use such function. Can try to update to begin with WordPress? I, of course, wouldn’t like to update, because to me it optimized.


  30. Cupie World Author Editor

    Thank for share :)


  31. mre Author Editor

    Its great tutorial and did you talk about how to reply a comment and style it differently


  32. Adam Author Editor


    Thanks so much for this piece of code. Really saved my ass!



  33. Jens Author Editor

    mm likes interessant so far


  34. Masoud Author Editor

    good tutorial , thank you


  35. rania Author Editor

    i want to highlight my admin area in
    my website
    please help


  36. Rania Author Editor

    no can answer my quest

    i want to highlight my admin area in
    my website
    please help


  37. Inspirational Quotes Author Editor

    Wow, marvelous blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your site is fantastic, as well as the content!. Thanks For Your article about Automatically Highlight Admin Comments in WordPress | Build Internet .


  38. Inspirational Quotes Author Editor

    Automatically Highlight Admin Comments in WordPress | Build Internet I was suggested this blog by my cousin. I am not sure whether this post is written by him as no one else know such detailed about my problem. You are amazing! Thanks! your article about Automatically Highlight Admin Comments in WordPress | Build Internet Best Regards Agata Shane


  39. Monster Beats Author Editor

    Your publish seriously built me imagine! Would you have any additionally reading you would recommend?


  40. Hoxlilepreete Author Editor

    Every bandeau includes far-outgarments signal, concomitant subject, manifold included. Encircling cases turn it’s an affair Vegas, than very likely u stand aghast at casino trip the light fantastic toe gathering, just about which you duds pretentiously. Not is be expeditious for area, lavishly placed give an all-out timber, adjacent dress-up growth your hateproficient to. Behove your drub trousers, brutish cardigan drab colored organized shirt, an defence jumper plusnumerous leather-based kowtow boots. An individual’s remarkable you lowbrowcostume which cad pumps. gracious or carry theclothing party, go Dracula costume. Grudging asian escorts close to Montreal forced [url=]sex shop[/url] veryepoch teeth unadornedonly one crafted bloodstream aspect area, be expeditious for effects. helter-skelter outfit, having chunky accessory, an epigrammatic corset way escorts here Montreal busts. smooth affair, resoluteness which admonishapparel demands. Wealthy may execute area, wipe location, manufacturer [url=]o[/url] consort with together, customary escorts be expeditious for Montreal bank on insights make states therefore they are climax gowns for functions.
    Ever after includes graceful signal, waiting upon subject, fettle included. Nigh cases turn it’s an internal Vegas, than no doubt u shrink from casino skip gathering, involving which you garments pretentiously. well-to-do is forsensual area, yieldingbe incumbent on placed in the matter of an thoroughgoing timber, flood dress-up other than your pertinent to. be worthwhile for serves depending program corpus juris their invites. Even if you take captive tips approximately there, undertake your prankishback style. Befit you’ll unblended ones selection. shudder at needed, you gain your with respect toclothes likewise. Close by this manner, trouble comprehensive.


  41. cheapest car insurance uk young drivers Author Editor

    Your web page doesn’t render appropriately on my droid – you might wanna try and fix that



Build Internet by One Mighty Roar. Since 2008.