Skip to content

Instantly share code, notes, and snippets.

@jchristopher
Created October 1, 2020 17:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchristopher/4cd10b7030051c79b3d1df73617fe872 to your computer and use it in GitHub Desktop.
Save jchristopher/4cd10b7030051c79b3d1df73617fe872 to your computer and use it in GitHub Desktop.
Store your recent Instagram posts as a WordPress transient. Simple. Might break. ¯\_(ツ)_/¯
<?php
// Super simple transient storage of the 4 most recent Instagramp posts.
// Stores only images/first image in carousel album.
// Assumes you already have an access token.
// Don't know if the access token invalidates over time. If it does, this doesn't handle it.
// Transient storage is an array of media objects directly from Instagram.
// Possible to sideload images into the Media library using https://developer.wordpress.org/reference/functions/media_sideload_image/
$transient_name = 'my_instagram_feed';
$access_token = 'change_me';
$number_of_posts = 4;
if ( empty ( $ig_feed = get_transient( $transient_name ) ) ) {
$response = wp_remote_get( 'https://graph.instagram.com/me/media?fields=id,username&access_token=' . $access_token );
if ( ! is_wp_error( $response ) ) {
if ( 200 == wp_remote_retrieve_response_code( $response ) ) {
$ig_feed = [];
$body = json_decode( wp_remote_retrieve_body( $response ), true );
foreach ( $body['data'] as $media ) {
$feed = wp_remote_get( 'https://graph.instagram.com/' . $media['id'] . '?access_token=' . $access_token . '&fields=id,media_type,media_url,username,timestamp' );
if ( 200 == wp_remote_retrieve_response_code( $feed ) ) {
$entry = json_decode( wp_remote_retrieve_body( $feed ), true );
if ( 'IMAGE' == $entry['media_type'] ) {
$ig_feed[] = $entry;
}
if ( 'CAROUSEL_ALBUM' == $entry['media_type'] ) {
$carousel_response = wp_remote_get( 'https://graph.instagram.com/' . $media['id'] . '/children?access_token=' . $access_token . '&fields=id,media_type,media_url,username,timestamp' );
if ( 200 == wp_remote_retrieve_response_code( $carousel_response ) ) {
$children = json_decode( wp_remote_retrieve_body( $carousel_response ), true );
$ig_feed[] = $children['data'][0];
}
}
if ( count( $ig_feed ) >= $number_of_posts ) {
break;
}
}
}
}
}
set_transient( $transient_name, $ig_feed, 12 * HOUR_IN_SECONDS );
}
var_dump( $ig_feed );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment