InstagramグラフAPIでハッシュタグ検索結果を出力する

参考文献

グラフAPIをたたいて出力するところの参考
https://navymobile.co.jp/instagram-graph-api

ハッシュタグのID番号を調べる方法の参考
https://qiita.com/1000VICKY/items/684a5702e160d0382d23

コード

<?php    
    // PHP
    $instagram = null; // JSONデータ配列をここに格納

    $instagram_business_id = '17841403059936174'; // InstagramビジネスアカウントのID
    $instagram_search_id = '17842315306069901'; // InstagramハッシュタグID
    $access_token = 'EAAqZAGrI1NBMBABmp4JbM9X8ZAygORKsZBCGZBCnmv5oBPJEZCGblZAnQ4lnXJmC6HRwBKHPVZABiYATr9LMmSUmFRipk3uw7C1MhKZCsHxeAXH1vyKjhdObTr0WrUZCGBo4h5AEA3ZCKf1BsalOQp3hRYXOQwq3li2O6njZA2jdLRV3QZDZD'; // 有効期限無期限のアクセストークン
    $post_count = 9; // 表示件数
    $query = 'media_url,media_type,comments_count,id,like_count,children{media_url,permalink},permalink,caption';
    $get_url = 'https://graph.facebook.com/v7.0/' . $instagram_search_id .'/recent_media?user_id=' . $instagram_business_id . '&fields=' . $query . '&limit='. $post_count .'&access_token=' . $access_token;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $get_url);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  // curl_execの結果を文字列で返す
    $response = curl_exec($curl);
    curl_close($curl);

    if($response){
      $instagram = json_decode($response);
      if(isset($instagram->error)){
          $instagram = null;
      }
    }
?>
    <?php if(is_array($instagram->data)): ?>
    <div class="instagram-container">
    <?php
    foreach($instagram->data as $post):
      $caption = $post->caption;
      $caption = preg_replace('/\n/', '<br>', $caption);
    ?>
      <div class="instagram-item">
        <a class="instagram-card" href="<?php echo $post->permalink; ?>" target="_blank" rel="noopener noreferrer">
         <?php if($post->media_type=='VIDEO'):?>
             <video src="<?php echo $post->media_url;?>"></video>
         <?php else:?>
          <img class="instagram-card__img" src="<?php echo $post->media_url;?>" alt="<?php echo $caption; ?>">
         <?php endif;?>
         </a>
      </div>
    <?php endforeach; ?>
    </div>
    <?php endif; ?>
.instagram-container{
  display: flex;
  flex-wrap: wrap;
}

.instagram-item{
  width: 33.333333%;
}

a.instagram-card{
  display: block;
  position: relative;
  margin-bottom: 16px;
}

.instagram-card__img{
  max-width: 100%;
  height: auto;
  display: block;
}

メモ:2時間くらい