Skip to content

Instantly share code, notes, and snippets.

@congthien
Last active March 18, 2018 17:03
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 congthien/c909760953d3e83a88bdbed4ddf891fc to your computer and use it in GitHub Desktop.
Save congthien/c909760953d3e83a88bdbed4ddf891fc to your computer and use it in GitHub Desktop.
if ( ! function_exists( 'onepress_scrape_instagram' ) ) {
function onepress_scrape_instagram( $username )
{
$username = strtolower($username);
$username = str_replace('@', '', $username);
$remote = wp_remote_get('https://instagram.com/' . trim($username));
if ( is_wp_error( $remote ) ) {
return false;
}
if ( 200 != wp_remote_retrieve_response_code($remote) ) {
return false;
}
$shards = explode('window._sharedData = ', $remote['body']);
$insta_json = explode(';</script>', $shards[1]);
$insta_array = json_decode($insta_json[0], TRUE);
if ( ! $insta_array )
return false;
if (isset( $insta_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'] )) {
$images = $insta_array['entry_data']['ProfilePage'][0]['graphql']['user']['edge_owner_to_timeline_media']['edges'];
} else {
return false;
}
if ( ! is_array( $images ) ) {
return false;
}
$instagram = array();
foreach ($images as $image) {
if ( true === $image['node']['is_video'] ) {
$type = 'video';
} else {
$type = 'image';
}
$caption = __( 'Instagram Image', 'onepress' );
if ( ! empty( $image['node']['edge_media_to_caption']['edges'][0]['node']['text'] ) ) {
$caption = $image['node']['edge_media_to_caption']['edges'][0]['node']['text'];
}
$instagram[] = array(
'title' => $caption,
'link' => trailingslashit( '//instagram.com/p/' . $image['node']['shortcode'] ),
'thumbnail' => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][4]['src'] ),
'small' => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][2]['src'] ),
'large' => preg_replace( '/^https?\:/i', '', $image['node']['thumbnail_resources'][4]['src'] ),
'full' => preg_replace( '/^https?\:/i', '', $image['node']['display_url'] ),
'type' => $type,
);
}
return $instagram;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment