• Brig01

    (@brig01)


    I’ve been trying lots and lots of different bit.ly 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 bit.ly 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 bit.ly 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 bit.ly login
    $apikey = 'API KEY'; //bit.ly apikey
    
    $short_url = json_decode(file_get_contents('https://api.bit.ly/v3/shorten?login='.$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 = "Bit.ly Error! ".$short_url->status_txt;
        }
        do_action('makeshorturl');
        return $short_url;
    }
    
    function shorturl_metabox() //create a meta box for each page and post in admin
    {
        if(is_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/>';
    }
    
    add_action('publish_post','makeshorturl');
    add_action('publish_page','makeshorturl');
    add_action('do_meta_boxes','shorturl_metabox');

    Then put the following in your template files where you want to display the bit.ly 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 ‘Bit.ly URL Function – Testing Request’ is closed to new replies.