I have this code on my functions.php for getting shorturl over bit.ly

function bitly() {
global $post;
$bitly = file_get_contents('http://api.bit.ly/v3/shorten?login=USER&apiKey=KEY&longUrl='.urlencode(get_permalink($post->ID)).'&format=txt');
echo $bitly;

but, sometimes i got error like this "Function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden in functions.php on line 614"

Line 614 is code from above. What i want is to handle that error and not show it for users. But instead of showing bit.ly short url, if error 404 is there, i want to show default wp.me url for users or if not possible wp.me then whole url.

EDIT I fixed this with this code

function bitly() {
global $post;
$bitly = wp_remote_retrieve_body (wp_remote_get('http://api.bit.ly/v3/shorten?login=USERNAME&apiKey=APIKEY&longUrl='.urlencode(get_permalink($post->ID)).'&format=txt'));
if( is_wp_error( $bitly ) ) {
echo wp_get_shortlink($post->ID); }
else { echo $bitly; }

1 Answer 1


I agree that this is PHP rather than WP question.

To bring it closer to WP I do suggest to take a look at following functionality:

  • HTTP API is highly suggested for making HTTP requests;
  • add_post_meta() and related meta functions to store post-specific information;
  • the_shortlink() function, that is suggested template tag to use for natvie short link functionality (and hook into for third party).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.