Cette page est également disponible en Français Français

Today I’ll show you how to shorten comment links, so we will talk about the comment_text function.


The problem

Did you noticed that on a lot of responsiv sites, when a visitor paste a long link in a comment, the layout badly react and sometimes adds a horizontal scrollbar. If it does not, it is not less ugly to have an full URL displayed in clear. This was the case on b*web – example here – until I take care of the subject.

The reason of this little problem is quite simple, an URL pasted in a comment is natively transform into link, but an URL is a sequence of characters with no spaces (and sometimes without dashes) so the browser interprets it as a single word and do not break the line.

The solution is actually quite simple, WordPress provides to us the comment_text function. The latter is already filtered by many functions as follows:


For our needs, we’ll add a new filter that will be applied after the URLs have been converted into links. The principle is simple, the new filter will parse the content returned by comment_text through a regular expression (REGEX) – just like for the_content – to retrieve the link, then shorten it and finally create a new one shorter and  less unsightly.


The solution

To use this filter, paste it in the files where your theme functions are located.


Note that the filter is applied on the comment displaying and not during it record, so you can seamlessly edit/delete the function later.

Brice Capobianco

WordPress addict and self-taught. I love to learn and to create, then to share…
Founder of b-website.com