Magic Tricks with URL’s (Part 1)
by Luke America on February 3, 2011
When we present URL's to our readers, we don't want to clutter the message with a long, inscrutable URL. Today, we'll look at different solutions to this occasional challenge.
We'll review a few URL-related functions available in WordPress. And, we'll look at their URL shortener function … while we develop a more visually appealing alternative. Plus, we'll code a routine that uses an online service which provides 'permanent' short link alternatives.
And as a bonus, we'll create a shortcode that makes it easier for you to generate links when you're using the dashboard editor in HTML mode. Let's get started.
The second part of this post is here.
Easy, Short Permalinks:
It's a common feature in many themes to list the permalink (post link) inside the postmeta section (categories and tags) for blog posts. Depending on your own site's URL and your specific permalink settings (Dashboard -> Settings -> Permalinks), the displayed permalink URL could be quite long.
A typical practice is to use a custom permalink structure like this: /blog/%postname%.html. You can read about the various structure tags here.
The following is one alternative. Just put the code in your theme's single.php file (or index.php if you don't have the former). It replaces the list of subdirectories with the simple post/page number. This way you can have both a standard permalink setting AND a different one that appears in your postmeta section.
Look for this code section:
<div class="postmeta">After the categories and tags, insert this line:
<p>Permalink: <?php $permalink=get_bloginfo('url') . "/?p=" . $post->ID; echo make_clickable($permalink);?></p>
The result will look like this:
Permalink: http://wpcodesnippets.info/?p=71
As an alternative (with 3.0+), you could insert this line:
<p>Permalink: <?php $permalink=wp_get_shortlink(); echo make_clickable($permalink);?></p>
The result of this one will look like this:
Permalink: http://wp.me/p1nBOf-19
Force Comment Links to Open in a New Browser Tab:
By default, WordPress filters a vistor's comments changing simple link text into a clickable link. However, those links open in the same browser tab navigating away from your site. Since most comment links are to another site, you may prefer to open them in a new browser tab.
Here's how to accomplish that. Put these lines in your functions.php file. This code doesn't change what's stored in the database. It only changes the displayed link … so … all of your existing comment links will now open in a new browser tab too. Plus, links to your own site open in the SAME browser tab. Cool, huh?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | add_filter('comment_text', 'wcs_force_comment_urls_popup', 101); function wcs_force_comment_urls_popup($comment) { $comment = popuplinks(make_clickable($comment)); $find_this = "/<a (.+?)[target='_blank'](.+?)>/i"; $comment = preg_replace_callback($find_this, 'wcs_local_link_self', $comment); return $comment; } function wcs_local_link_self($matches) { $this_site = site_url(); $this_site = str_replace('http://', '', $this_site); $this_site = str_replace('https://', '', $this_site); $this_site = str_replace('www.', '', $this_site); if (stristr($matches[0], $this_site)) { $output = str_replace('_blank', '_self', $matches[0]); $output = str_replace(' rel=\'external\'', '', $output); $output = str_replace(' rel="nofollow"', '', $output); } else { $output = $matches[0]; } return $output; } |
We set the filter priority to '101' so that it should be the last filter to process comments. In the function wcs_force_comment_urls_popup, line #7 is a regular expression to find anchor tags. The code in the next line sends matches to our callback function. When you need to make a decision based on a regular expression, callbacks are quite useful.
Our callback function wcs_local_link_self strips off the URL's protocol and www. Next, we determine if the link is to our own blog. If so, we replace '_blank' with '_self' and some other clean up. Otherwise, we return the string unscathed.
Basic WordPress URL Functions:
- esc_url() sanitizes URL's against whitelisted URL's. The defaults are: http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, and telnet. It also strips invalid characters.
- esc_url_raw() reformats URL's for clean insertion into the database.
- url_encode() encodes query strings for standards compliance in constructing URL's. This is similar to the PHP functions urlencode() and rawurlencode().
- url_encode_deep() URL encodes a list stored in an array.
- sanitize_email() strips out characters that aren't allowable in an email.
Extended WordPress URL Functions:
wp_make_link_relative() is a misnomer. It doesn't generate a true relative path. It simply strips the protocol, port, server, and site from the URL. Generally, this removes the common http://www/TLD prefix. Here's an example.
$long_url = "http://www.mylongsitename.com/onefolder/another/myfile.php"; $short_url = wp_make_link_relative($long_url); echo $short_url . '<br/>'; // output is: /onefolder/another/myfile.php
popuplinks() takes the HTML anchor code for a link and adds target='_blank' and rel='external'.
make_clickable() takes a text URL and converts it to full HTML anchor code. If the http:// isn't included, it's added. It's used to convert URL's typed in comments. This function is cool if you've never seen it before.
But, it's actually used throughout the PHP industry. Probably the only reason it's not a part of the language itself is that it is, in fact, ubiquitous. We should also mention that this function does NOT open the clicked link in a new browser tab. For that, you have to subsequently invoke popuplinks().
This brings us to the WordPress function to shorten URL's, url_shorten(). It chops the original text at the first 32 characters and appends ellipsis points. Also, this function is not available for use outside the dashboard (admin area). Here's an example usage.
$long_url = 'http://www.mylongsitename.com/onefolder/another/myfile.php'; $short_url = url_shorten($long_url); echo $short_url . '<br/>'; // output is: mylongsitename.com/onefolder/ano...
Let's Build Our Own URL Shortener:
Our function will compact the displayed link in the middle so that relevant portions (TLD and page) are readable. This doesn't change the link that search engines will reference. It only modifies the text that appears on the screen … so that long URL's don't wrap around to a second line.
Plus, we have an option to return clickable HTML code. The real magic is performed with preg_replace() using a regular expression. Basically, we take equal lengths from the left and right of the given URL and concatenate them back together with ellipsis points.
Take a look at the source code. In the second part of this article, we're going to construct a handy shortcode (macro) using this function. Be SURE to put both of them in your theme's functions.php file.
Introducing url_ShortenEx()…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | function url_ShortenEx($url_path, $max_length=40, $clickable=true, $target='_blank') { // shortens path in the middle so relevant parts are readable // optionally returns a clickable link with specified target // allow for override if only wanting the clickable feature if ($max_length <=0) {$max_length = 255;} if ((strlen($url_path) < $max_length) || ($max_length < 20)) { if ($clickable == true) { $url_path = make_clickable($url_path); $url_path = popuplinks($url_path); if ($target != '_blank') { $url_path = str_replace('_blank', $target, $url_path); } } return $url_path; } $out_path = $url_path; // uncomment next line to strip 'HTTP://' from output // $out_path = str_replace('http://', '', $url_path); $ellipsis = '...'; // can also use … or … $max_length -= strlen($ellipsis); $max_left = round($max_length/2); $max_right = $max_length - $max_left; $out_path = preg_replace('/(?<=^.{' . $max_left . '}).{4,}(?=.{' . $max_right . '}$)/', $ellipsis, $out_path); if ($clickable == true) { if ((strlen($url_path) > 4) && (strtolower(substr($url_path, 0, 4) != "http"))) { $url_path = 'http://' . $url_path; } $out_path = '<a href="' . $url_path . '">' . $out_path . '</a>'; $out_path = popuplinks($out_path); if ($target != '_blank') {$out_path = str_replace('_blank', $target, $out_path);}; } return $out_path; } |
And, here are three test results.
// test #1 $long_url = 'http://www.google.com'; $short_url = url_ShortenEx($long_url, 32); echo $short_url . '<br/>'; // the output is a clickable link displaying this text: // http://www.google.com // test #2 $long_url = 'http://www.mylongsitename.com/onefolder/another/myfile.php'; $short_url = url_ShortenEx($long_url, 32, false); echo $short_url . '<br/>'; // the output is a clickable link displaying this text: // http://www.mylongsi...myfile.php // test #3 $short_url = url_ShortenEx($long_url); echo $short_url . '<br/>'; // the output is a clickable link displaying this text: // http://www.mylongsiten...ther/myfile.php
In the next part of this post, we'll use an online service to create short links and we'll reveal a shortcode that makes it very easy to use the url_ShortenEx() function while writing your posts.
The second part of this post is here.
Subscribe to our RSS feed
Follow Us on Twitter



good stuff. thx
Lot’s of cool stuff here … my fourth visit! Keep ‘em comin