Skip to content

Instantly share code, notes, and snippets.

@kalenjohnson
Created January 5, 2015 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kalenjohnson/d147561697e6795efb5f to your computer and use it in GitHub Desktop.
Save kalenjohnson/d147561697e6795efb5f to your computer and use it in GitHub Desktop.
class InstagramFeed {
protected $keys;
public function __construct($user_id, $access_code)
{
$this->keys = [
'user_id' => $user_id,
'access_code' => $access_code,
];
}
public function getImages()
{
/**
* Check the WP Cache if the feed is there
* If it is, return that.
*/
$cache_name = 'Competitor_Instagram_feed';
$cache = get_transient($cache_name);
if ($cache) return $cache;
/**
* If it's not cached, build it
*/
$images = $this->buildFeed();
/**
* If it's a WP error, return the error
* Do this before saving the error in cache
*/
if ( is_wp_error($images) ) return $images;
/**
* Cache the images for one hour
*/
set_transient($cache_name, $images, 1 * HOUR_IN_SECONDS);
return $images;
}
private function buildFeed()
{
$feed = $this->getFeed();
/**
* If feed is not got'n, put up an error.
*/
if ($feed === null) return new WP_Error(400, 'Could not connect to Instagram');
$images = [];
foreach ($feed->data as $image)
{
$images[] = $image->images;
}
return $images;
}
private function getFeed()
{
$url = "https://api.instagram.com/v1/users/{$this->keys['user_id']}/media/recent/?access_token={$this->keys['access_code']}";
return json_decode($this->fetchData($url));
}
private function fetchData($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment