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.
[…] WordPress community has published an interesting tip that I think many people will find helpful. Styling the people’s name in your comment replies walks you through the steps to add a custom function to your functions.php file, then calling that […]
Interesting idea.. wonder how this works out?
p.s. thanks for sharing.
@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?
@Dawn: It is installed, but you forgot the colon 😉
About the plugin, I guess I could do that… I’ll let you know when I make one.
@Wessley: Nice author styling! Anyway to make this work with and without the colon. For people like Dawn?
@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 😉
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
useful tips thanks for sharing
Comments are closed.