How to shorten the comment_author() output on Wordpress
I have recently made a theme for a friend’s blog that don’t like to have long user pseudo or trackback title in comments. If the comment_author () output is too long, some part of the text overflows the div box. Even if it can be fixed through CSS, I thought – and because it’s not a good thing to modify core files in wordpress – I needed to create a special function to achieve my friend’s goal. Here’s how to do so :
So, we just have to modify the comment_author() function (which is located in wp-include/comment-template.php line 47) and set up a new function that we will call comment_author_short(). We will insert in the function file of your theme. By doing so you’ll avoid to see this function disappearing after your next wordpress update. Now, the code.
Initial function :
function comment_author() { $author = apply_filters('comment_author', get_comment_author() ); echo $author; }
New function
function comment_author_short() { $author = apply_filters('comment_author', get_comment_author() ); $chaine = $author; $max=35; if(strlen($chaine)>=$max){$chaine=substr($chaine,0,$max); $espace=strrpos($chaine," "); $chaine=substr($chaine,0,$espace)."..."; } echo $chaine; }
Because I’m not a native developer, I’ve no problem to explain that this code snippet shorten the output, echos the the shorten string (here chaîne, in french), and that you can change the maximum value by modifying the $max value (here, 35 characters), but I won’t explain the details.
Then, we just have to modify the file comments.php (or different file in your Wordpress theme folder that deals with comments template). To do so, search for the comment_author() function (via ctrl+f on windows) and add “_short” to its end. It must look like that :
<?php echo comment_author_short() ; ?>
And so, you will be able to have clean trackbacks in your comments, and avoid people letting comments with a long name. I will probably make a little Wordpress plugin in order to make it simple for people that prefer not to enter inside Wordpress’s code.
source of the shortening snippet : Php scripts (fr)