fbpx

How to display Instagram photos on your WordPress site using latest Instagram API?

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:

Create long-lived token

  1. Go to https://developers.facebook.com/
  2. Click My Apps > Create App

  3. Follow on screen instruction to create App ID
  4. Click “Add a Product” from created app.
  5. Find “Instagram Graph API” in products list and click “Set Up”
  6. Next, click “Create New App” 
  7. Input your site link in “Valid OAuth Redirect URIs”, “Deauthorize Callback URL”, “Data Deletion Request URL” field and click “Save changes”.
  8. After this, you need to add tester. Click “Add or Remove Instagram Testersunder User Token Generator section then click “Add Instagram Testers”
  9. After done add tester, the user need to go “Apps and Websites” tab of their Instagram profile to accept the invitation.


  10. Last, go back to Basic Display, click “Generate Token” on User Token Generator section.
  11. The user then need to give permission to access their Instagram medias. 
  12. After user permission given, copy and save the token for next steps.

Get user ID

Create plugin to display Instagram photos

Copy code below. Refer get_instagram_media.php for more information.

				
					<?php 
/**
* Get Instagram media on WordPress using the current Instagram (Facebook) API
*
* @param $token // Info on how to retrieve the token: https://www.gsarigiannidis.gr/instagram-feed-api-after-june-2020/
* @param $user // User ID can be found using the Facebook debug tool: https://developers.facebook.com/tools/debug/accesstoken/
* @param int $limit // Add a limit to prevent excessive calls.
* @param string $fields // More options here: https://developers.facebook.com/docs/instagram-basic-display-api/reference/media
* @param array $restrict // Available options: IMAGE, VIDEO, CAROUSEL_ALBUM
*
* @return array|mixed // Use it like that (minimal example): get_instagram_media(TOKEN, USER_ID);
*/
function get_instagram_media(
	$token,
	$user,
	$limit = 10,
	$fields = 'media_url,permalink,media_type,caption',
	$restrict = [ 'IMAGE' ]
) {
	// The request URL. see: https://developers.facebook.com/docs/instagram-basic-display-api/reference/user
	$request_url = 'https://graph.instagram.com/' . $user . '?fields=media&access_token=' . $token;

	// We use transients to cache the results and fetch them once every hour, to avoid bumping into Instagram's limits (see: https://developers.facebook.com/docs/graph-api/overview/rate-limiting#instagram-graph-api)
	$output = get_transient( 'instagram_feed_' . $user ); // Our transient should have a unique name, so we pass the user id as an extra precaution.
	if ( false === ( $data = $output ) || empty( $output ) ) {
		// Prepare the data variable and set it as an empty array.
		$data = [];
		// Make the request
		$response      = wp_safe_remote_get( $request_url );
		$response_body = '';
		if ( is_array( $response ) && ! is_wp_error( $response ) ) {
			$response_body = json_decode( $response['body'] );
		}
		if ( $response_body && isset( $response_body->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:

				
					<?php
    $photos = get_instagram_media( 'TOKEN', 'USER_ID');
    if($photos) : ?>
<?php foreach ( $photos as $photo ) : ?>
<a href="<?php echo esc_url( $photo->permalink ); ?>" target="_blank">
    <img decoding="async" src="<?php echo $photo->media_url; ?>" alt="<?php echo htmlspecialchars( mb_substr( $photo->caption, 0, 60 ) ); ?> ...">
</a>
<?php endforeach; ?>
<?php endif;?>

				
			

“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.

Scroll to Top