I've recently wrote a little script that get's my Twitter feed and caches it to save on HTTP requests. Without WordPress it works great, as soon as I add it to WordPress everything goes wrong, which makes sense because file_get_contents doesn't particularly work correctly in WordPress. I tried using: wp_remote_get() instead but I just get the following error:
Fatal error: Cannot use object of type WP_Error as array in
which is this line:
$tweets = json_decode($contents['body']);
Code without adding to WordPress: (Which works fine)
$file = "tweets.txt";
if (@file_exists($file) and @filemtime($file)>=strtotime("-10 minutes")) {
$tweets = json_decode(file_get_contents($file));
} else {
$tweets = file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jack&include_rts=true");
$fh = fopen($file, 'w');
fwrite($fh, $tweets);
fclose($fh);
$tweets = json_decode($tweets);
}
$i = 0;
foreach($tweets as $tweet) {
$tweetText = preg_replace('#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#','<a href="$1">$1</a>', $tweet->text);
$tweetText = preg_replace('/(^|\s)@([a-z0-9_]+)/i','$1<a href="http://www.twitter.com/$2">@$2</a>', $tweetText);
$tweetText .= " - " . date('G:i F jS',strtotime($tweet->created_at));
echo '<p>'.$tweetText.'</p>';
++$i;
if ($i==3) {break;}
}
Code when adding to WordPress:
$file = "tweets.txt";
if (@file_exists($file) and @filemtime($file)>=strtotime("-10 minutes")) {
$contents = wp_remote_get($file);
$tweets = json_decode($contents['body']);
} else {
$tweets = wp_remote_get("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jack&include_rts=true");
$fh = fopen($file, 'w');
fwrite($fh, $tweets);
fclose($fh);
$tweets = json_decode($contents['body']);
}
$i = 0;
foreach($tweets as $tweet) {
$tweetText = preg_replace('#\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))#','<a href="$1">$1</a>', $tweet->text);
$tweetText = preg_replace('/(^|\s)@([a-z0-9_]+)/i','$1<a href="http://www.twitter.com/$2">@$2</a>', $tweetText);
$tweetText .= " - " . date('G:i F jS',strtotime($tweet->created_at));
echo '<p>'.$tweetText.'</p>';
++$i;
if ($i==3) {break;}
}
I'm quite new to using HTTP requests like JSON. I'm sorry if I left anything out and/or this becomes a really easy solution. Thanks.