Skip to content

Instantly share code, notes, and snippets.

@ryanscherler
Created June 29, 2020 23:39
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 ryanscherler/d7742d1d9f2a261e58583aa0792033a2 to your computer and use it in GitHub Desktop.
Save ryanscherler/d7742d1d9f2a261e58583aa0792033a2 to your computer and use it in GitHub Desktop.
WP Theme Class: Query Instagram API via GraphQL / Zttp
<?php
namespace Theme;
use Illuminate\Support\Collection;
use Zttp\Zttp;
class Instagram {
protected $cache_mins;
public $username;
public $limit;
public $data;
/**
* New instagram instance
*
* @param string $username
*/
public function __construct($username, $limit = 12, $cache_mins = 5)
{
$this->username = $username;
$this->limit = $limit;
$this->cache_mins = $cache_mins;
$this->data = $this->fetchData();
}
/**
* Get instagram data
*
* @return object
*/
private function fetchData()
{
$transient_key = 'instagram_blog_id_'.get_current_blog_id();
if (($data = get_transient($transient_key)) === false) {
$url = 'https://instagram.com/graphql/query/?query_id=17888483320059182&variables={"id":"'.$this->username.'","first":'.$this->limit.',"after":null}';
$response = Zttp::get($url);
$result = json_decode($response);
$data = $result->data->user;
set_transient($transient_key, $data, $this->cache_mins * MINUTE_IN_SECONDS);
}
return $data;
}
/**
* Get media helper
*
* @return Illuminate\Support\Collection
*/
public function media() {
$edges = $this->data->edge_owner_to_timeline_media->edges;
$media = new Collection([]);
if ($edges) {
foreach ($edges as $edge) {
$node = $edge->node;
$media->put($node->id, [
'shortcode' => $node->shortcode,
'caption' => isset($node->edge_media_to_caption->edges[0]) ? $node->edge_media_to_caption->edges[0]->node->text : '',
'thumbnails' => $node->thumbnail_resources,
'comment_count' => $node->edge_media_to_comment->count,
'likes' => $node->edge_media_preview_like->count,
]);
}
}
return $media;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment