Plugin: Auto-hyperlink URLs

This plugin has been updated! Comments to this post are now closed. For the latest download, documentation, and link for posting new comments related to this plugin, visit the plugin’s new homepage at:
coffee2code.com/wp-plugins/auto-hyperlink-urls
Name:
Auto-hyperlink URLs
Author:
Scott Reilly
Version:
2.01
Last updated:
10 October 2004
Description:

Auto-hyperlink text URLs in post content and comment text to the URL they reference. Does NOT try to hyperlink already hyperlinked URLs. Improves upon WordPress’s default make_clickable function, along with adding some configuration options (such as link truncation).

Notes:

This plugin seeks to address certain shortcomings with WordPress’s default auto-hyperlinking function (make_clickable()) (which itself was borrowed from phpBB). This tweaks the pattern matching expressions to prevent inappropriate adjacent characters from becoming part of the link (such as a trailing period when a link ends a sentence, links that are parenthesized or braced, comma-separated, etc) and it prevents invalid text from becoming a mailto: link (i.e. [email protected]) or for invalid URIs (i.e. blah) from becoming links. In addition, this plugin adds configurability to the auto-hyperlinker such that you can configure:

– If you want auto-hyperlinked text URLs to only show the hostname
– If you want auto-hyperlinked text URLs truncated after N characters
– If you want auto-hyperlinked text URLs to open in new browser window or not
– Text to come before and after the link text for truncated links

This plugin will recognize any protocol-specified URI (http|https|ftp|news)://, etc, as well as e-mail addresses. It also adds the new ability to recognize Class B domain references (i.e. “somesite.net” where not just those prepended with “www.”) as valid links (i.e. “wordpress.org” would now get auto-hyperlinked)

Installation:
  1. Download the file autohyperlink-urls.zip and unzip it into your /wp-content/plugins/ directory.
    -OR-
    Copy and paste the the code ( autohyperlink-urls.phps ) into a file called autohyperlink-urls.php, and put that file into your /wp-content/plugins/ directory.
  2. Optional: Modify any configuration options (presented as defaults for the arguments to the function hyperlink_urls())
  3. Activate the plugin from your WordPress admin ‘Plugins’ page.
Functions:
[I’ve defined the $num_posts arg as 2 for all of the examples in order to limit the amount of sample output.]

function c2c_hyperlink_urls ($text, $mode='0', $trunc_before='', $trunc_after='...', $open_in_new_window=true)

  • $text : The text to search for plain-text URLs which should be hyperlinked
  • $mode : How the text part of the newly created hyperlinks should appear. Assume as an example “http://wordpress.org/support/10”
    • 0 = The full text of the URL (ie. “http://wordpress.org/support/10”)
    • 1 = Host-only (ie. “http://wordpress.org”)
    • 11+ = (Any number greater than 11 will result in only that many characters appearing in the link.)
  • $trunc_before : Text/HTML to appear before each link created when $mode is 0 or 11+ and truncation occurs
  • $trunc_after : Text/HTML to appear after each link created when $mode is 0 or 11+ and truncation occurs
  • $open_in_new_window : Boolean value (either ‘true’ or ‘false’) to determine whether all created hyperlinks should open a new window when the link is clicked by a visitor; default is ‘true’.
Tips & Examples:

Example:

“wordpress.org”, appearing un-hyperlinked in post text or comment text, becomes:
<a href=”http://wordpress.org” title=”http://wordpress.org” target=”_blank”>wordpress.org</a>

Assume the following text appears in a post/comment: “http://www.somesite.org/with/a/very/long/url/that/may/break/your/sites/layout”

$mode = 0
=> www.somesite.org/with/a/very/long/url/that/may/break/your/sites/layout

$mode = 1, $trunc_before='[‘, $trunc_after=’]’
=> [http://www.somesite.org]

$mode=25
=> www.somesite.org/w…

Related Links:
  • WordPress Support Forum announcement for Auto-hyperlink URLs
Release Log:
  • 10 Oct 2004 : v2.01 — Fix to once again prevent linking already hyperlinked URL
  • 27 Sep 2004 : v2.0 —
    • Plaintext URLs can now begin, end, or be all of the post and it will get auto-hyperlinked
    • Incorporated some WP1.3 regular expression changes to make_clickable()
    • Added “gov” and “edu” to the list of common domain extensions (for Class B domain support)
    • No longer displays the protocol (the “http://” part) in the displayed link text
    • Dropped support for auto-linking aim: and icq:
    • Prepended function names with “c2c_” to avoid potential future conflict with other plugins or the WordPress core
    • Changed license from BSD-new to MIT
  • 13 Jul 2004 : v1.01 — Slight tweak to prevent blah from becoming a link
  • 13 Jul 2004: v1.0 — Complete rewrite
  • 08 Jul 2004 : v0.9 — Released to the public
Copyright & Disclaimer:

Copyright (c) 2004 by Scott Reilly (aka coffee2code)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Acknowledgements:
This plugin is an improvement over code that originated with phpBB and further modified by WordPress.

136 thoughts on “Plugin: Auto-hyperlink URLs

  1. I just activated it after grabbing the smilies plugin and it broke the smilie plugin…they are all linked back to my site via blah so your code works…I am going to try and
    tweak it so it will ignore links with smilie in it…

  2. Ahh I have never worked with php so I am not really sure how to modify it basically I want to add a clause that if smilies is part of the url then dont convert it…could you help me out
    a bit…thanks el

  3. Turns out WordPress has something like this plugin already. Except it only auto-hyperlinks URLs in comments. However, it does have the unfortunate knack of picking up a trailing “.” (so that if you put the URL at the end of a sentence and end it with a period, the period becomes part of the link). I guess sit tight and I’ll see about modifying the WordPress function a bit. In my initial attempts to get it to auto-hyperlink in the post text, it didn’t always do it when it should’ve, though except for the trailing-period thing I mentioned above, it seems to be a champ in the comments section.

  4. Scott I have been tinkering with the PHP code but no luck so far resolving the smilie issue. Here is the link that I am trying to search for
    beatloverradio.com/wp-images/smilies/* if this is found I dont want it to be auto converted. Here are my two ideas

    1. within your code if I could search for that string and if it is found then tell the replacement function not to replace it
    2. Have the function imediatly sort out these refrences in the $text before passing it on to the rest of the function…

    I have a feeling the first approach is going to be the better one

  5. Scott, where can I get WP plug-in?

    I installed yours, but I got the classic

    
    Warning: Cannot modify header information - headers already sent by
    error. I checked and there is nothing before the &lt;?php or after the ?&gt;.

    I mostly just need it for comments, so either one would be fine for me. Thanks again!

  6. elpierco: I’m not sure what you’re trying to do. Are you trying to write un-hyperlinked text like http://beatloverradio.com/wp-images/smilies/ and not have this plugin link it (much as how it isn’t linked where I just wrote it)? Or are you saying text is getting auto-linked before it can be evaluated by the smilie plugin? Also, what smilie plugin are you referring to?

    Ruby: WP has an auto-hyperlinker built in, but it’s only activated for the comments text. So if you simply type a text link into a comment, WP will auto-link it for you. I’m looking into tweaking it out if I can and then having it apply to post text as well.

  7. I was looking for something like this, having just modified wp-mail.php do do something similar for incoming emails, but I would much rather have this a system wide preference/option. Is that what you are aiming for when you say “I’ll see about modifying the WordPress function a bit”?

    I’m wondering if I should wait on your work.

    By the way, the function I found also truncates the displayed link to a set size, which is a big help to not breaking a fixed pixel layout.

    I’m happy to share.

  8. Plugin updated to v1.0

    This plugin has been updated to v1.0. It improves upon WordPress’s built-in auto-linking function, make_clickable(). The problems mentioned above should no longer be an issue. Also, it now has the ability to truncate link text after N characters, present links only by their hostname, and to output text before and/or after each link that gets truncated.

    To upgrade, just overwrite your previous autohyperlink_urls.php file with this one, perform any configuration customizations you want, and you should be good to go.

  9. Scott,
    Unfortunately, this version seems to have broken deleting posts in WP. I went to delete a post after activating your plugin and got the following message:
    Warning: Cannot modify header information - headers already sent by (output started at /home/geodog/public_html/strangelove/wp-content/plugins/autohyperlink-urls.php:109) in /home/geodog/public_html/strangelove/wp-admin/post.php on line 474

  10. That warning usually indicates that there is a space before the opening &lt;?php or after the ending ?> of the file. Can you verify if that is the case or not? (Try obtaining the plugin file via the .zip and not the .phps if you couldn’t find a space and if you originally hadn’t obtained the file from the .zip).

  11. I like this. But just one little problem. It doesn’t have ‘gov’ in the list of ‘common URLs’. Since I work for the U.S. Geological Survey (www.usgs.gov), this showed up pretty fast. I added it to the list. Here’s a patch in case you want to add it to the default:

    — autohyperlink-urls.php Wed Aug 11 09:13:54 2004
    +++ autohyperlink-urls.php.orig Wed Aug 11 09:15:50 2004
    @@ -69,7 +69,7 @@
    function truncate_link ($url, $mode=’0′, $trunc_before=”, $trunc_after=’…’)
    {
    if (1 == $mode) {
    $url = preg_replace(“/(([a-z]+?):\/\/[a-z0-9\-\.]+).*/i”, “$1
    “, $url);
    – $url = $trunc_before . preg_replace(“/([a-z0-9\-\.]+\.(com|org|
    net|us|gov|info|biz|ws|name|tv)).*/i”, “$1”, $url) . $trunc_after;
    + $url = $trunc_before . preg_replace(“/([a-z0-9\-\.]+\.(com|org|
    net|us|info|biz|ws|name|tv)).*/i”, “$1”, $url) . $trunc_after;
    } elseif (($mode > 10) && (strlen($url) > $mode)) {
    $url = $trunc_before . substr($url, 0, $mode) . $trunc_after;
    }
    @@ -85,8 +85,8 @@
    “‘\1‘ . truncate_link(“$2”
    , “$mode”, “$trunc_before”, “$trunc_after”) . ‘
    ‘”,
    $text);

    – // Hyperlink common URLs *.(com|org|net|us|gov|info|biz|ws|name|tv)(/*)
    – $text = preg_replace(“#([\n\(\[ ])([a-z0-9\-\.]+)\.(com|org|net|us|gov|info
    |biz|ws|name|tv)(\/[a-z0-9\-\.\~\/]+)?((?:/[^,< \n\r]*)?)#ie", + // Hyperlink common URLs *.(com|org|net|us|info|biz|ws|name|tv)(/*) + $text = preg_replace("#([\n\(\[ ])([a-z0-9\-\.]+)\.(com|org|net|us|info|biz |ws|name|tv)(\/[a-z0-9\-\.\~\/]+)?((?:/[^,< \n\r]*)?)#ie", "'\1‘ . truncate_link(“$2.$3$4”, “$mode”, “$trunc_before”, “$trunc_after\
    “) . ‘‘”,
    $text);

  12. I believe I have found another bug in your plugin. If I create an entry with www.test.com, it’ll hyperlink it as normal. But if I then write a comment with and mention www.test.com, it won’t link to it.

    However, without your plug-in it would have linked to the site in the comment as normal.

    Or more simply, your plug-in auto-hyperlinks to URLs in the blog entry, but deactivates the normal hyperlink functionality in the comment.

    Note that this only applies to www.test.com. If I wrote a comment with www.test.com, it would hyperlink to it as normal.

  13. Hmm, then again it’s linking as normal on your blog. I assume you’re using your own plug-in. (Are you?)

    If so, any idea why it might not link on other sites??

  14. Plugin updated to v2.0

    This release features these changes:

    * Plaintext URLs can now begin, end, or be all of the post and it will get auto-hyperlinked
    * Incorporated some WP1.3 regular expression changes to make_clickable()
    * Added “gov” and “edu” to the list of common domain extensions (for Class B domain support)
    * No longer displays the protocol (the “http://” part) in the displayed link text
    * Dropped support for auto-linking aim: and icq:
    * Prepended function names with “c2c_” to avoid potential future conflict with other plugins or the WordPress core
    * Changed license from BSD-new to MIT

  15. I installed our plugin and got the same problem.. it’s not working… I’m using plain wp1.2 ,,, haven’t switched over to mingus,,, do I need to switch over to mingus?

  16. I’ve run into an odd little problem. The archives on my site are ported from some old hand-coded HTML, which didn’t use the (/p) to close the paragraphs (assume angle brackets instead of parenthesiseses there). As such, WordPress adds in a string oe (/p)s at the end of the entry, one for each (p) in the entry. And my posts frequently end with a URL. When the plug-in sees the URL followed by a string of (/p)s, it’s interpreting those (/p)s as part of the URL, shoving them into the link and causing various odd problems as a result. Basically, I end up with a link with a bad URL and which displays a quote sign and a close angle bracket as part of the link text.

    For an example, scroll down to the end of AAUGH.com/wordpress/index.php?m=200008

  17. One thing of note for users using URLs with the two-letter country code suffixes (and wanting to hyperlink plaintext URLs that AREN’T prepended with “http://”)… the plugin by default only recognizes “.us”. If you want to add support for your country code, look for this bit in the plugin’s code:

    (com|org|net|gov|edu|us|info|biz|ws|name|tv)

    Then add your country like so (I’ll assume you want to add “.uk”):

    (com|org|net|gov|edu|us|info|biz|ws|name|tv|uk)

    In the future I may add support for other country codes (or perhaps all of them, depending on my assessment of feasibility).

    But just to be clear: Beginning a valid plaintext URL with “http://” will ALWAYS result in that being created into a proper link, regardless of what country code you may be using. The country code limitation only comes into play if you don’t prepend “http://”, such as writing “example.com.uk”, which by default won’t consider the “.uk” as part of the link.

    Nat: When I update this plugin I’ll try to ensure that your problem gets fixed, but for now I’ve noted that what you’ve described is true.

    Adam: When you manually create links in your posts (i.e., actually using the link tags and not relying on this plugin), do your links remain links in the feed? A quick glance at the WP code suggests that all tags get stripped, but if your manual links survive then I’ve mistook what is happening.

  18. I’m getting an error – using wp 1.5, after I add the plugin it is trying to create multiple headers while in the admin area. It seems as if the final result on the /wordpress page is working ok, but the errors scare me. Any ideas?

    Also, the automatic email updater plugin.. when I send an email with a regular text url i.e. www.msn.com, it gets formatted in my email as (www.msn.com) and does not show in the blog (the parentheses represent brackets) – any way to fix this? Otherwise, awesome plugin!

  19. Denis and Marc: I will be looking into it within the week.

    Mark: Fixed in the latest version of the plugin, to be released very soon.

    james: The error is probably caused by the inclusion of spaces before the <?php at the start of the file, or more likely, spaces or other characters after the ?> at the end of the file.

  20. Hi,

    I have text emails that come through like this:

    Those two little braket things somehow stop the script from truncating the hyperlink.

    I know so little about php that I don’t know where to add them into the script to make the script take them out too.

    Can anyone help me with this?

    Kindly,
    John

  21. geeshh… I can’t seem to add those characters to my posts. But it is the less-than and greater-than characters. The one over the comma on your keyboard and the one over the period.

    My hyperlinks start with the less-than sign and they end with the greater-than sign. Can I somehow make it so the script will still work when my incoming text hyperlinks are surrounded by these two characters?

    Kindly again,
    John

Comments are closed.