Magic Tricks with URL’s (Part 2)

by on February 7, 2011

Continuing from Part 1, today we'll code a routine that uses an online service which provides 'permanent' short link alternatives.

And 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.

Let's Construct a Useful Shortcode:

With the dashboard editor, you have vastly more control of the output by using HTML mode. But, one downside is having to type the full anchor code for links. This shortcode will help by shrinking your keystroke count almost in half.

In it's simplest form, the shortcode can be used like this:
[wcs_link www.google.com]

This will generate the following HTML code on the finished page.

Code: HTML

<a href="http://www.google.com" rel="nofollow" target='_blank' rel='external'>http://www.google.com</a>

25 keystrokes will generate 105 characters that you might have had to type otherwise! Now, think about this. How many times a month do you type links in your posts? Actually, the rel  HTML anchor attributes were added automatically by WordPress; but, you do save many keystrokes with shortcodes.

Note that when you use this shortcode with ONLY the link, you should NOT enclose the link in quotes (single or double). In fact, as a general rule when using shortcodes, you don't need to quote the attribute values UNLESS there are spaces in them OR the value itself starts with an equals sign.

WordPress shortcode macros can save you a LOT of time over the months of blogging! They are our friends … embrace them.

Here's another example: [wcs_link link=www.google.com text=Google.com]

This one is a little more detailed, but you still only needed to type 48 characters … saving you a whopping 57 keystrokes.

Here's the full usage syntax.
[wcs_link link=YOUR_LINK text='DISPLAYED TEXT' target=WINDOW maxlength=VALUE]

Note, however, that all of the attributes except link are optional. And, if it's the only attribute, you don't even have to type the attribute name link itself (as in the first example usage above).

Also, for convenience, we've added the capability to use the attribute name url or link.

Plus, if you run a multi-user site (WPMU or WP 3.0+) with multiple blogs/users, the others will appreciate this convenience you offer to them.

Okay, let's look at the source code for wcs_link[].

Code: PHP (plus WordPress)Shortcode: wcs_link

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
45
46
47
48
49
50
51
add_shortcode('wcs_link', 'wcs_link_shortcode_handler');
 
function wcs_link_shortcode_handler($atts)
{
    if (sizeof($atts) == 1)
    {
        $url_path = $atts['0'];
 
        // bonus for WP blog links on the same site (w/out attribute name)
        if ((strlen($url_path) > 3) && (strtolower(substr($url_path, 0, 3) == '?p=')))
        {
            $url_path = site_url() . '/' . $url_path;
            return url_ShortenEx($url_path, 40, true, '_self');
        }
 
        return url_ShortenEx($url_path);
    }
 
    $parms = shortcode_atts(array('link' => '', 'url' => '', 'text' => '', 'target' => '_blank', 'maxlength' => '40'), $atts);
 
    $link = $parms['link'];
    $url = $parms['url'];
    if ($link == '') {$link = $url;}
 
    $text = $parms['text'];
    $target = $parms['target'];
    $maxlength = $parms['maxlength'];
 
 
    if ($link == '') {return 'ERROR';}
 
 
    // bonus for WP blog links on the same site
    if ((strlen($link) > 3) && (strtolower(substr($link, 0, 3) == '?p=')))
    {
        $link = site_url() . $link;
        $target = '_self';
    }
 
    if ($text == '') {return url_ShortenEx($link, $maxlength, true, $target);}
 
    if ((strlen($link) > 4) && (strtolower(substr($link, 0, 4) != "http")))
    {
        $link = 'http://' . $link;
    }
    $out_path = '<a href="' . $link . '">' . $text . '</a>';
    $out_path = popuplinks($out_path);
    if ($target != '_blank') {$out_path = str_replace('_blank', $target, $out_path);};
 
    return $out_path;
}

Did you notice the added bonus? How many times do you link to other articles on you own blog? This very article does so (linking back to part 1).

Here's the actual code that does it.

Code: PHP (plus WordPress)

The first part of this post is [wcs_link url='?p=71' text='here'].

And, here's the result:
The first part of this post is here.

Where do you get that post/page ID? The easiest way is to go to your dashboard and click Posts in the sidebar. In the list that then displays on the right, hover over any post title. Now, while hovering look in the status bar of your browser. You'll see a portion like this “post=”. The number immediately following this is your Post ID. It works the same way for pages.

Also, while you're editing a page, the same “post=” will be in your address bar.

 Shortcode Usage Reference: wcs_link

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
Usage
Simple Usage:    [wcs_link www.google.com]
Common Usage:    [wcs_link link=www.google.com title='Visit Google']
Same Site Usage: [wcs_link link=?p=123 title='My Other Page']
Full Usage:      [wcs_link link=www.google.com title='Visit Google' target=_self maxlength=50]
 
Defaults
link        none     (the url of the site)
title       none     (the text displayed for the end-user)
target      _blank   (can be: _self, _blank, _top, or _parent)
maxlength   40       (numeric > 20) (ellipsis dots in the center)
 
Notes
* The attribute name "url" can be used as an alias of "link".
* If you only include the link value, omit the url/link attribute name.
* As with all shortcodes, the sequence of attributes doesn't matter.


Remember, you must include both the shortcode source and the url_ShortenEx() PHP code in your theme's functions.php file. And best of all, you have the PHP source code so that you modify it to suite your needs.

Accessing TinyUrl.com with Code:

Most savvy web users today have heard of TinyUrl.com. Initially, Twitter.com automatically translated all long URL's using this service.

But, what isn't common knowledge is that you can access their service from your own PHP code.

It's rather simple. Here's a function to do just that. With the second (optional) attribute set to false, the returned string will be a permanent shortened URL (text only). The default is true which returns a clickable link that opens in a new browser tab.

Here's getTinyUrl():

Code: PHP (plus WordPress)Function: getTinyUrl()

1
2
3
4
5
6
7
8
9
function getTinyUrl($url, $clickable=true)
{
    $tinyurl = file_get_contents("http://tinyurl.com/api-create.php?url=" . $url);
    if ($clickable == true)
    {
        $tinyurl = popuplinks(make_clickable($tinyurl));
    }
    return $tinyurl;
}

Here are some alternative sites that create permanent short links for long URL's. There are others. But, over the last couple of years several of these services have closed.

Also, the Google Service offers their API access for PHP programmer's (provided you get a free API key for your site). In closing, here are two references for using this service.

Share This Article: “Magic Tricks with URL's (Part 2)”

(Also Available: Press CTRL+D to Bookmark this Page)

Comments

Share Your Thoughts  7 Responses to “Magic Tricks with URL’s (Part 2)”
  1. 1
  2. 2
    SEO says:

    I love to disseminate information that I’ve accumulated through the season to
    help enhance group overall performance.

    Feel free to surf to my web site – SEO

  3. 3
    slow pitch says:

    If you are going for best contents like me, simply pay a quick visit this website all the time for
    the reason that it gives feature contents, thanks

  4. 4

    I savour, result in I found just what I was taking a look for.
    You’ve ended my 4 day lengthy hunt! God Bless you man.
    Have a nice day. Bye

  5. 5

    With havin so much content do you ever run into any problems
    of plagorism or copyright violation? My site has a lot of completely unique content I’ve either created
    myself or outsourced but it appears a lot of it is popping it up all over the web without my authorization. Do you know any ways to help reduce content from being stolen? I’d genuinely appreciate
    it.

  6. 6

    There is a chemical reaction between DHA and the amino acids on the top most layer of the skin. When you
    buy leather goods, especially expensive leather goods, you want to take care of them.
    Elbows (on the inside and outside of the arms), backs of knees,
    inner thighs, bust area and even ankles are
    skin segments prone to rapid degeneration of the spray tan product.
    So before using a particular London salon it is worthwhile to see
    whether the staff employed there have the correct qualifications and public liability insurance.
    Does your travel insurance policy provide sufficient cover for any medical eventuality and repatriation. First and foremost, never spray the face first especially if they have never had a
    spray tan before and don’t know what to expect. * The tanning booths are very effective and you have complete privacy.

    Remember, the dry skin is one of the greatest enemies of the successful tanning.
    It’s also important to do any shaving required at this stage and not shave again for up to
    24 hours after the spray tanning application. 98, Self-Tan Bronzing Spray for a natural-looking golden tan 6.

    Take a look at my webpage; spray tan salons

  7. 7

    The reader gets the feeling that the robotics companies made the contract not only
    to prevent a robot uprising, but also to discourage any sympathetic humans form sheltering androids who want to gain full civilian rights.
    Whereas it may have been months to even a year before a i – Phone game
    was available on Android, it now is taking
    just several weeks because they know how important it is to get their application out as
    soon as possible. The e mails really contain a locked picture of the first frame of your video and when your recipient clicks on the play button they redirected to a locked website that
    really plays the video, however the way this is done is well enough no one is going to
    be distracted by such a minor detail.

Share Your Thoughts

(Some editor features are restricted unless you're logged in.)

(When replying to a specific comment, your browser may require Shift+Enter instead of just Enter.)


(get a gravatar)


Notify me of followup comments via e-mail. You can also subscribe without commenting.