Skip to content

Instantly share code, notes, and snippets.

@dboutote
Created February 15, 2017 18:46
Show Gist options
  • Save dboutote/739b086861831e2116c803f5e6fbf0e7 to your computer and use it in GitHub Desktop.
Save dboutote/739b086861831e2116c803f5e6fbf0e7 to your computer and use it in GitHub Desktop.
Quick and dirty Instagram scraper
<?php
/**
* Instagram scraper
*
* Quick and dirty Instragram scraper for displaying a Instagram feed.
*
* Based on : https://gist.github.com/cosmocatalano/4544576
*
* @param string $username Instagram user account
* @param int $numphotos Number of photos to display
*
* @return array $insta_feed Array of images data.
*/
function np_scrape_instagram( $username = '' , $numphotos = 6 ) {
if( ! $username ){
return new WP_Error( 'empty_username', __( 'Empty user name.') );
}
$remote = wp_remote_get( 'https://instagram.com/' . trim( $username ) );
if( is_wp_error( $remote ) ){
return new WP_Error( 'site_down', __( 'Unable to communicate with Instagram.' ) );
}
if ( 200 != wp_remote_retrieve_response_code( $remote ) ){
return new WP_Error( 'invalid_response', __( 'Instagram did not return a valid response.' ) );
}
$shards = explode( 'window._sharedData = ', $remote['body'] );
$insta_json = explode( ';</script>', $shards[1] );
$insta_array = json_decode( $insta_json[0], true );
if ( ! $insta_array ){
return new WP_Error( 'bad_json', __( 'Instagram returned invalid data.' ) );
}
$images = ( isset( $insta_array['entry_data']['ProfilePage'][0]['user']['media']['nodes'] ) )
? $insta_array['entry_data']['ProfilePage'][0]['user']['media']['nodes']
: '' ;
$insta_feed = array();
if( $images ) :
foreach ( $images as $image ) {
$insta_feed[] = array(
'id' => $image['id'],
'description' => $image['caption'],
'link' => sprintf( '//www.instagram.com/p/%s/', $image['code'] ),
'time' => $image['date'],
'comments' => $image['comments']['count'],
'likes' => $image['likes']['count'],
'thumbnail' => $image['thumbnail_src'],
'type' => $image['__typename'],
'height' => $image['dimensions']['height'],
'width' => $image['dimensions']['width'],
);
}
endif;
return array_slice( $insta_feed, 0, $numphotos );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment