What is Instagram API?
API stands for application programming interface which we can use it to interact with Instagram and get user profile or media.
How to display Instagram photos on your WordPress site?
Prerequisite:
- Public Instagram account
- Token
- User ID
Create long-lived token
- Go to https://developers.facebook.com/
- Click My Apps > Create App
- Follow on screen instruction to create App ID
- Click “Add a Product” from created app.
- Find “Instagram Graph API” in products list and click “Set Up”
- Next, click “Create New App”
- Input your site link in “Valid OAuth Redirect URIs”, “Deauthorize Callback URL”, “Data Deletion Request URL” field and click “Save changes”.
- After this, you need to add tester. Click “Add or Remove Instagram Testers” under User Token Generator section then click “Add Instagram Testers”
- After done add tester, the user need to go “Apps and Websites” tab of their Instagram profile to accept the invitation.
- Last, go back to Basic Display, click “Generate Token” on User Token Generator section.
- The user then need to give permission to access their Instagram medias.
- After user permission given, copy and save the token for next steps.
Get user ID
Get user id from https://developers.facebook.com/tools/debug/accesstoken/
Create plugin to display Instagram photos
Copy code below. Refer get_instagram_media.php for more information.
media->data ) ) {
$i = 0;
// Get each media item from it's ID and push it to the $data array.
foreach ( $response_body->media->data as $media ) {
if ( $limit > $i ) {
$request_media_url = 'https://graph.instagram.com/' . $media->id . '?fields=' . $fields . '&access_token=' . $token;
$media_response = wp_safe_remote_get( $request_media_url );
if ( is_array( $media_response ) && ! is_wp_error( $media_response ) ) {
$media_body = json_decode( $media_response['body'] );
}
if ( in_array( $media_body->media_type, $restrict, true ) ) {
$i ++;
$data[] = $media_body;
}
}
}
}
// Store the data in the transient and keep if for an hour.
set_transient( 'instagram_feed_' . $user, $data, HOUR_IN_SECONDS );
// Refresh the token to make sure it never expires (see: https://developers.facebook.com/docs/instagram-basic-display-api/guides/long-lived-access-tokens#refresh-a-long-lived-token)
wp_safe_remote_get( 'https://graph.instagram.com/refresh_access_token?grant_type=ig_refresh_token&access_token=' . $token );
$output = $data;
}
return $output;
}
Get photo by calling function:
get_instagram_media(‘your access token’, ‘your user id’)
The output is in array type. Replace “your access token” and “your user id” with the token generated and the user id in previous steps.
To echo the results properly can refer code below:
“get_instagram_media” can pass up to 5 parameters. You can modify number of entries to fetch, field to return and media type by passing it through parameter. Hope this article helps you in display Instagram photos. Check the sample now.