Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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; }
}
share|improve this question

1 Answer 1

up vote 4 down vote accepted

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).
share|improve this answer
    
+1 .. Good suggestions there mate.. :) –  t31os Dec 20 '10 at 10:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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