Home Articles Styling the people’s name in your comment replies

Styling the people’s name in your comment replies

1284
9
SHARE

You may have noticed that many people use the syntax @name in blog comments for addressing messages to a specific person. Maybe you’re one of them. In this tutorial we’ll learn how to style that piece of text differently so it stands out better.

The Function

First, we’re going to create a function in the functions.php file of our WordPress Theme. This function needs to find the specific piece of text ‘@name’, where name can be anything. Our best option here is using a regular expression. Here it is:

function atPeople($comment){
    return preg_replace("/@([^:]*):s/", "@$1: ", $comment);
}

Pretty simple eh! What this does is finding an @ symbol followed by text and then a colon “:”. For example: “@john:”. Then it replaces that for a span object that we can easily style later.

The Hook

Creating the function is not enough, we need WordPress to call that function with every comment. That’s where the hook comes in:

add_filter('comment_text', 'atPeople');

That little piece of code just tells WordPress to apply our function to the comment text. It also needs to be in the functions.php file, by the way.

The Styling

Ok, now we’re ready to style our span object, which is the easier part. You can do whatever you want with it, you can make it bold, change it’s color, make it bigger, the possibilities are endless. We’re just going to make it bold and red. Here we go:

.atPeople{
    font-weight: bold;
    color: red;
}

And that, of course, needs to go at the end of the style.css file of your WordPress theme.

That’s it, hope you enjoyed this tutorial.

9 COMMENTS

  1. @Prof kienstra Let’s see if it works (if it’s insalled n here!)

    Its a great idea, any chance of amking it a plugin so it doesn’t get overwritten when you upgrade WP?

  2. @Danny: It’s complicated… I did this with the colon, thinking of people whose names aren’t just one word long. If the colon wasn’t there I can’t tell how many of the words after the @ are actually the person’s name. Plus Ozh’ Absolut Comments plugin inserts the @ and the colon, which is just awesome 😉

  3. Thank you for this tutorial! I’ve just got around to implementing it on my non-live test site and it was easy as pie – I had been putting it off because I was nervous about breaking something in my theme… never hacked the PHP “myself” before. So thank you double!

    Ricky

Comments are closed.