Skip to content

Instantly share code, notes, and snippets.

@mt-deva
Forked from chrisvanpatten/readme.md
Last active December 19, 2017 06:11
Show Gist options
  • Save mt-deva/981fc04b9bb2f4efaf34 to your computer and use it in GitHub Desktop.
Save mt-deva/981fc04b9bb2f4efaf34 to your computer and use it in GitHub Desktop.
Super-simple way to grab a few Instagram images and cache them w/ WordPress

This is an easy way to integrate a basic Instagram feed into a WordPress site.

<?php
/**
* Get Instagram Posts
*
* Returns an array of posts in the following format:
* content - Image Url
* platform - instagram as String
* popularity - Total number of Likes
* url - Link to view the image on instagram
* date - date it was posted
*
* This function utilises Wordpress Transients to cache the request and refesh every hour.
*
* @param int $count Maximum number of items to return from the instagram request, Instagram limits this to 20 per request
* @param str $resolution Change the resolution of the items to return: low_resolution, standard_resolution
* @return array
*
*/
function get_instagram($user_id = '', $count = 20, $resolution = 'low_resolution'){
if (get_transient('instagram_feed_' . $user_id)) {
return get_transient('instagram_feed_' . $user_id);
} else {
$access_token = '';
$instagram = wp_remote_get('https://api.instagram.com/v1/users/'. $user_id .'/media/recent/?access_token=' . $access_token . '&count=' . $count);
$instagram = json_decode($instagram['body']);
$instagramPosts = [];
for ($i = 0; $i < $count; $i++) {
$post = $instagram->data[$i];
$instagramPosts[(int)
$post->created_time] = [
'content'=>$post->images->{$resolution}->url,
'platform'=>'instagram',
'popularity'=>$post->likes->count,
'url'=>$post->link,
'date'=>date('M j,Y', $post->created_time)
];
}
set_transient('instagram_feed_' . $user_id, $instagramPosts, HOUR_IN_SECONDS);
// newest first
krsort($instagramPosts);
return $instagramPosts;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment