Support » Plugins » URL Function – Testing Request

  • I’ve been trying lots and lots of different scripts in the last few weeks but none have worked the way I wanted.

    Some doesn’t work at all and some work but slow down the site as they call the API on every page load.

    So I’ve finally finished my own function which is a mix of several examples I’ve found.

    It calls the API only once for each page or post and stores the URL in a meta key for future use.

    I haven’t tested the script much yet so if someone else would like to test it as well and let me know if it works OK I would be very happy.

    Here’s the code that should be placed in functions.php.

    function makeshorturl()
    global $post;
    $url = get_permalink($post->ID); //the long url
    $login = 'USERNAME'; //your login
    $apikey = 'API KEY'; // apikey
    $short_url = json_decode(file_get_contents(''.$login.'&apiKey='.$apikey.'&longURL='.urlencode($url).'&format=json')); //create bitly url
    if($short_url->status_code=="200") //make sure bitly returned OK response
    		if(get_post_meta($post->ID, "bitly_url", true) != ""){ //check if a bitly url already exists for this page or post, if it does pull from meta instead of calling bitly
    			$short_url = get_post_meta($post->ID, "bitly_url", true);
    		else //if bitly url doesn't exist create it and save it to meta for future use
    			$short_url = $short_url->data->url;
    			add_post_meta($post->ID, 'bitly_url', $short_url, true);
        else //make us aware if there's an error with the bitly api
            $short_url = " Error! ".$short_url->status_txt;
        return $short_url;
    function shorturl_metabox() //create a meta box for each page and post in admin
            add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','post','side');
            add_meta_box('bitlyurl',__('Short URL','short-url'),'showshorturlbox','page','side');
    function showshorturlbox() //display the meta box
        echo '<label for="bitlyurl">'.__('Shortened URL','short-url-label').': '.makeshorturl().'</label><br/><br/>';

    Then put the following in your template files where you want to display the URL

    <?php echo get_post_meta($post->ID, 'bitly_url', true); ?>

    IMPORTANT: Existing content must be re-saved/updated for the function to kick in. I haven’t worked out yet how to automatically update existing content.

    Hope this can help someone at least!

  • The topic ‘ URL Function – Testing Request’ is closed to new replies.