Skip to content

Get all photos from Instagram which have a specific hashtag with PHP

To get all photos from Instagram that have a specific hashtag with PHP, you can use the Instagram Graph API (part of the Meta Developer Platform).

To use the current API, you'll need to:

  1. Create a Meta App and link an Instagram Business or Creator account
  2. Generate a User Access Token using OAuth 2.0
  3. Retrieve the hashtag ID via the /hashtags endpoint
  4. Use the access token and hashtag ID to fetch media, handling cursor-based pagination

Here's some sample code that demonstrates how to use the Instagram Graph API to get photos with a specific hashtag:

Example of getting all photos from Instagram which have a specific hashtag with PHP

php
<?php

// Note: You must obtain a valid User Access Token and Hashtag ID via the Meta Developer Platform first.
// This example assumes you already have these values for brevity.
$access_token = 'YOUR_ACCESS_TOKEN';
$hashtag_id = 'YOUR_HASHTAG_ID'; // e.g., from GET /{ig-user-id}/hashtags
$limit = 20; // Instagram Graph API maximum limit per request

$base_url = 'https://graph.facebook.com/v18.0';
$hashtag_url = $base_url . '/' . $hashtag_id . '/media';

$params = http_build_query([
    'access_token' => $access_token,
    'limit' => $limit
]);

$curl = curl_init($hashtag_url . '?' . $params);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPGET, true);
$response = curl_exec($curl);
curl_close($curl);

$result = json_decode($response);

if (isset($result->data)) {
    foreach ($result->data as $photo) {
        echo $photo->media_url . "\n";
    }

    // Handle pagination using the 'after' cursor
    if (isset($result->paging->cursors->after)) {
        $next_cursor = $result->paging->cursors->after;
        // In a production script, loop until no 'after' cursor remains
        echo "Next cursor: " . $next_cursor . "\n";
    }
} else {
    echo "No photos found or API error.\n";
}
?>

I hope this helps! Let me know if you have any questions.

Dual-run preview — compare with live Symfony routes.