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  13 Responses to “Magic Tricks with URL’s (Part 2)”
  1. 1
  2. 2
    My Site says:

    Howdy!
    Someone in my Facebook group shared this website with us
    so I came
    to take a look. I’m definitely enjoying the
    information. I’m bookmarking andd will be tweeting this to my followers!

    Fantastic blog and
    terrific style
    and design.

  3. 3

    We absolutely love your blog and find many of your post’s to
    be just what I’m looking for. Do you offer guest writers to write content available
    for you? I wouldn’t mind composing a post or elaborating on most of
    the subjects you write regarding here. Again, awesome web site!

  4. 4

    Having your App pre-built to a particular level and submitted to the App stores should
    cost you no more than five to six hundred dollars for both platforms.
    Due to the massive growth in the market, you no longer have to pay thousands
    for a fully functional customized App, but keeping costs to
    a minimum requires understanding the various
    methods of having your App built as well as the various
    platforms on which they can be built. If you attract the attention of top bloggers, they can do the mobile app marketing for you.

  5. 5

    This excellent website certainly has all the information I needed about this subject and didn’t know who
    to ask.

  6. 6

    Sweet blog! I found it while browsing on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?

    I’ve been trying for a while but I never seem to get there!
    Thanks

  7. 7

    Good day! I could have sworn I’ve visited this website before but after looking at many of the
    posts I realized it’s new to me. Nonetheless, I’m certainly
    delighted I stumbled upon it and I’ll be bookmarking it and checking back regularly!

    Also visit my site Premiere Source Of Surgery Related Articles

  8. 8

    Heya i’m for the first time here. I found this board and I find
    It really useful & it helped mme out a lot. I hope to give something back aand aidd others like you aided me.

    Have a look at my blog post :: Straighten hair Naturally milk

  9. 9

    Only 10 people used bear spray against charging bears.

    You don’t have to hit the bird dead-center either – as long as you strike within the general
    hit window, you should have no trouble taking the duck down.
    If you’ve never seen the film before, or are just revisiting it, this is one release that is a must-own.

    my web page :: deer hunter 2014 cheats

  10. 10

    Thankѕ forr yοur marvelous posting! І actuаlly enjoyed reading іt, ʏou coսld be a great author.

    I will ensure thatt Ӏ bookmark уߋur blog aոd will oftеn cme Ьack
    verу soon. I wwnt tο encourage tҺat you continue your ǥreat work, have a nice holiday weekend!

    Feel free tto visit mү weblog photography jobs

  11. 11

    These are genuinely great ideas in about blogging.
    You have touched some pleasant things here. Any way keep up
    wrinting.

  12. 12

    Very shortly tҺiѕ web page աill be famous amid all
    blogfging aand site-building people, ɗue tо it’s fastidious articles or
    reviews

    Мy web-site :: Pure Green Coffee Beans

  13. 13

    Thanks for taking this opportunity to
    discuss this, I appreciate with this and if you have some more
    information please share it with me.

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.